Skip to content

Commit 633fa97

Browse files
committed
feat(json-crdt): 🎸 implement view .read() retrieval method
1 parent 76910e2 commit 633fa97

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

src/json-crdt/model/api/ModelApi.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,18 @@ export class ModelApi<N extends JsonNode = JsonNode> implements SyncStore<JsonNo
266266
return this.model.view();
267267
}
268268

269+
/**
270+
* Reads the value at the given path in the model. If no path is provided,
271+
* returns the root node's view.
272+
*
273+
* @param path Path at which to read the value.
274+
* @returns The value at the given path, or the root node's view if no path
275+
* is provided.
276+
*/
277+
public read(path?: ApiPath): unknown {
278+
return this.r.read(path);
279+
}
280+
269281
private inTx = false;
270282
public transaction(callback: () => void) {
271283
if (this.inTx) callback();
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import {Model} from '../../Model';
2+
3+
describe('.read()', () => {
4+
test('can retrieve own view', () => {
5+
const doc = Model.create();
6+
doc.api.root({
7+
arr: [1, 2, 3],
8+
});
9+
const arr = doc.api.arr(['arr']);
10+
expect(arr.read()).toEqual([1, 2, 3]);
11+
expect(arr.read('')).toEqual([1, 2, 3]);
12+
expect(arr.read([])).toEqual([1, 2, 3]);
13+
});
14+
15+
test('can retrieve array element', () => {
16+
const doc = Model.create();
17+
doc.api.root({
18+
arr: [1, 2, 3],
19+
});
20+
const arr = doc.api.arr(['arr']);
21+
expect(arr.read('/0')).toEqual(1);
22+
expect(arr.read([0])).toEqual(1);
23+
expect(arr.read('/2')).toEqual(3);
24+
expect(arr.read([2])).toEqual(3);
25+
expect(arr.read(['2'])).toEqual(3);
26+
});
27+
28+
test('retrieve deep within document', () => {
29+
const doc = Model.create();
30+
doc.api.root({
31+
foo: 'bar',
32+
obj: {
33+
nested: {
34+
value: 42,
35+
deep: {
36+
another: 'value',
37+
},
38+
},
39+
},
40+
arr: [1, 2, {
41+
nested: [1, 2, 3],
42+
deep: {
43+
value: 4
44+
}
45+
}],
46+
});
47+
expect(doc.api.r.read('/foo')).toEqual('bar');
48+
expect(doc.api.read('/foo')).toEqual('bar');
49+
expect((doc.s as any).foo.toView()).toEqual('bar');
50+
});
51+
});

src/json-crdt/model/api/nodes.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,10 @@ export class NodeApi<N extends JsonNode = JsonNode> implements Printable {
175175
return this.node.view() as unknown as JsonNodeView<N>;
176176
}
177177

178+
public read(path?: ApiPath): unknown {
179+
return !path ? this.view() : this.in(path).view();
180+
}
181+
178182
public proxy(): types.ProxyNode<N> {
179183
return {
180184
toApi: () => <any>this,

0 commit comments

Comments
 (0)