-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
OpTest.ts
61 lines (54 loc) · 1.88 KB
/
OpTest.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import type {CompactTestOp, OPCODE_TEST} from '../codec/compact/types';
import {OperationTest} from '../types';
import {find, Path, formatJsonPointer} from '../../json-pointer';
import {AbstractPredicateOp} from './AbstractPredicateOp';
import {OPCODE} from '../constants';
import {AbstractOp} from './AbstractOp';
import {deepEqual} from '../../json-equal/deepEqual';
import type {IMessagePackEncoder} from '@jsonjoy.com/json-pack/lib/msgpack';
/**
* @category JSON Patch
* @category JSON Predicate
*/
export class OpTest extends AbstractPredicateOp<'test'> {
constructor(
path: Path,
public readonly value: unknown,
public readonly not: boolean,
) {
super(path);
}
public op() {
return 'test' as 'test';
}
public code() {
return OPCODE.test;
}
public test(doc: unknown) {
const {val} = find(doc, this.path);
if (val === undefined) return !!this.not;
const test = deepEqual(val, this.value);
return this.not ? !test : test;
}
public toJson(parent?: AbstractOp): OperationTest {
const op: OperationTest = {
op: 'test',
path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
value: this.value,
};
if (this.not) (op as any).not = this.not;
return op;
}
public toCompact(parent: AbstractOp | undefined, verbose: boolean): CompactTestOp {
const path = parent ? this.path.slice(parent.path.length) : this.path;
const opcode: OPCODE_TEST = verbose ? 'test' : OPCODE.test;
return this.not ? [opcode, path, this.value, 1] : [opcode, path, this.value];
}
public encode(encoder: IMessagePackEncoder, parent?: AbstractOp) {
encoder.encodeArrayHeader(this.not ? 4 : 3);
encoder.writer.u8(OPCODE.test);
encoder.encodeArray(parent ? this.path.slice(parent.path.length) : (this.path as unknown[]));
encoder.encodeAny(this.value);
if (this.not) encoder.writer.u8(1);
}
}