Constructor on subobject
Relik77 opened this issue · comments
Hi,
For a schema I want to use a custom constructor to slightly modify the values before using them:
import * as SchemaObject from "schema-object";
const StatsSchema = new SchemaObject({
a_stat_value : "number"
});
const PageSchema = new SchemaObject({
page_id: "number",
// other page properties
Stats: StatsSchema
}, {
constructors : {
default: function (values) {
console.log("PageSchema values", values)
// values can like : { page_id: "number", Stats: { a_stat_value: "number" } }
// or { page_id: "number", a_stat_value: "number" } : stats properties and page properties merged
// I need to separate page properties and stats properties (to standardize an API return)
// So i use :
values.Stats = values.Stats ? values.Stats : values;
this.populate(values);
}
}
});
const SiteSchema = new SchemaObject({
// other site properties
Pages: [PageSchema]
});
// I test the schema
let site = new SiteSchema ({
Pages: [{
page_id: 1,
Stats: { a_stat_value: 1 }
}, {
page_id: 2,
a_stat_value: 1
}]
})
console.log(JSON.stringify(site, null, 4))
PageSchema values {}
PageSchema values {}
{
"Pages": [
{
"page_id": 1,
"Stats": {
"a_stat_value": 1
}
},
{
"page_id": 2
}
]
}
Values in PageSchema constructor has empty !
NB: If i remove this.populate(values);
in PageSchema constructor, the result is same. (While the expected behavior would be to have a sub object empty : uninitialized)