diff --git a/packages/entity/src/resources/entity.js b/packages/entity/src/resources/entity.js index c258cfe..e397b5c 100644 --- a/packages/entity/src/resources/entity.js +++ b/packages/entity/src/resources/entity.js @@ -389,4 +389,33 @@ export default (latus) => class Entity extends decorate(JsonResource) { return Object.keys(this.#traits); } + static withDefaults(json) { + const Traits = latus.get('%traits'); + return { + ...json, + traits: Object.entries(json.traits) + .reduce((r, [type, traitJson]) => ({ + ...r, + [type]: Traits[type] + ? Traits[type].withDefaults(traitJson) + : traitJson, + }), {}), + }; + } + + static withoutDefaults(json) { + const Traits = latus.get('%traits'); + const without = { + ...json, + traits: Object.entries(json.traits) + .reduce((r, [type, traitJson]) => ({ + ...r, + [type]: Traits[type] + ? Traits[type].withoutDefaults(traitJson) + : traitJson, + }), {}), + }; + return without; + } + }; diff --git a/packages/traits/src/trait.js b/packages/traits/src/trait.js index ca4437b..351fc2e 100644 --- a/packages/traits/src/trait.js +++ b/packages/traits/src/trait.js @@ -154,10 +154,33 @@ export default class Trait extends decorate(JsonResource) { } toJSON() { + return this.constructor.withoutDefaults(this); + } + + static withDefaults(json) { return { - params: this.params, - state: this.state, + params: this.defaultParamsWith(json.params || {}), + state: this.defaultStateWith(json.state || {}), }; } + static withoutDefaults(json) { + const without = {}; + const defaultParams = this.defaultParams(); + Object.entries(json.params || {}).forEach(([key, value]) => { + if (JSON.stringify(value) !== JSON.stringify(defaultParams[key])) { + without.params = without.params || {}; + without.params[key] = value; + } + }); + const defaultState = this.defaultState(); + Object.entries(json.state || {}).forEach(([key, value]) => { + if (JSON.stringify(value) !== JSON.stringify(defaultState[key])) { + without.state = without.state || {}; + without.state[key] = value; + } + }); + return without; + } + }