From 50cca7bb9f316aeba6a4c8ab2e395b6d175a542b Mon Sep 17 00:00:00 2001 From: cha0s Date: Tue, 22 Mar 2022 17:58:38 -0500 Subject: [PATCH] refactor(entity): JSON --- packages/entity/src/resources/entity.js | 37 +++++++++++++++++++------ packages/entity/test/json.js | 4 +-- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/packages/entity/src/resources/entity.js b/packages/entity/src/resources/entity.js index 8283879..606be6e 100644 --- a/packages/entity/src/resources/entity.js +++ b/packages/entity/src/resources/entity.js @@ -371,16 +371,35 @@ export default (flecks) => { } toJSON() { - const json = {}; - const traits = Object.entries(this.#traits); - for (let i = 0; i < traits.length; i++) { - const [type, trait] = traits[i]; - json[type] = trait.toJSON(); + let output; + if (this.uri) { + const pristine = {}; + const json = {}; + const traits = Object.entries(this.#traits); + for (let i = 0; i < traits.length; i++) { + const [type, trait] = traits[i]; + pristine.traits = pristine.traits || {}; + pristine.traits[type] = trait.constructor.withDefaults( + this.#originalJson ? this.#originalJson.traits[type] : {}, + ); + json.traits = json.traits || {}; + json.traits[type] = trait.toJSON(); + } + output = { + extends: this.uri, + ...(mergeDiff(pristine, json) || {}), + }; } - return { - ...(this.uri ? {extends: this.uri} : {}), - traits: json, - }; + else { + output = {}; + const traits = Object.entries(this.#traits); + for (let i = 0; i < traits.length; i++) { + const [type, trait] = traits[i]; + output.traits = {}; + output.traits[type] = trait.toJSON(); + } + } + return output; } toNetwork(informed) { diff --git a/packages/entity/test/json.js b/packages/entity/test/json.js index 517a920..37818a8 100644 --- a/packages/entity/test/json.js +++ b/packages/entity/test/json.js @@ -25,9 +25,9 @@ afterEach(() => { it('outputs JSON', () => { const entity = new Entity(); - expect(entity.toJSON()).to.deep.equal({traits: {}}); + expect(entity.toJSON()).to.deep.equal({}); entity.uri = '/foo/bar'; - expect(entity.toJSON()).to.deep.equal({extends: entity.uri, traits: {}}); + expect(entity.toJSON()).to.deep.equal({extends: entity.uri}); }); it('can trim defaults from JSON', async () => {