Skip to content

Commit 3e5c0fa

Browse files
authored
Merge pull request #604 from witheve/json-null
Add a sentinel value for nulls in JSON
2 parents fae4bbf + 82364cb commit 3e5c0fa

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/runtime/util/eavs.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,14 @@
55
import {Changes} from "../changes";
66
import {TripleIndex} from "../indexes";
77

8+
const JSON_NULL_ID = "external|json|null";
9+
810
//---------------------------------------------------------------------
911
// JS conversion
1012
//---------------------------------------------------------------------
1113

1214
export function fromJS(changes: Changes, json: any, node: string, scope: string, idPrefix: string = "js") {
15+
if(json === null || json === undefined) return JSON_NULL_ID;
1316
if(json.constructor === Array) {
1417
let arrayId = `${idPrefix}|array`;
1518
changes.store(scope, arrayId, "tag", "array", node);
@@ -26,10 +29,15 @@ export function fromJS(changes: Changes, json: any, node: string, scope: string,
2629
let objectId = `${idPrefix}|object`;
2730
for(let key of Object.keys(json)) {
2831
let value = json[key];
29-
if(value !== null && (value.constructor === Array || typeof value === "object")) {
30-
value = fromJS(changes, value, node, scope, `${objectId}|${key}`);
32+
if(value === null || value === undefined) {
33+
changes.store(scope, JSON_NULL_ID, "tag", "json-null", node);
34+
changes.store(scope, objectId, key, JSON_NULL_ID, node);
35+
} else {
36+
if(value.constructor === Array || typeof value === "object") {
37+
value = fromJS(changes, value, node, scope, `${objectId}|${key}`);
38+
}
39+
changes.store(scope, objectId, key, value, node);
3140
}
32-
changes.store(scope, objectId, key, value, node);
3341
}
3442
return objectId;
3543
} else {
@@ -39,6 +47,7 @@ export function fromJS(changes: Changes, json: any, node: string, scope: string,
3947

4048
export function toJS(index: TripleIndex, recordId) {
4149
let result;
50+
if(recordId === JSON_NULL_ID) return null;
4251
let isArray = index.lookup(recordId, "tag", "array");
4352
if(isArray !== undefined) {
4453
result = [];

test/eavs.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,11 @@ test("converting nested js objects and arrays", (assert) => {
4848
}, assert);
4949
assert.end();
5050
})
51+
52+
test("converting with null roundtrips", (assert) => {
53+
convert({
54+
beep: null,
55+
foo: [1, null, 2]
56+
}, assert);
57+
assert.end();
58+
})

0 commit comments

Comments
 (0)