refactor: better defaults

This commit is contained in:
cha0s 2021-01-28 00:13:56 -06:00
parent 4b16583600
commit 7ca213712a
2 changed files with 54 additions and 2 deletions

View File

@ -389,4 +389,33 @@ export default (latus) => class Entity extends decorate(JsonResource) {
return Object.keys(this.#traits); 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;
}
}; };

View File

@ -154,10 +154,33 @@ export default class Trait extends decorate(JsonResource) {
} }
toJSON() { toJSON() {
return this.constructor.withoutDefaults(this);
}
static withDefaults(json) {
return { return {
params: this.params, params: this.defaultParamsWith(json.params || {}),
state: this.state, 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;
}
} }