2020-04-14 13:13:45 +02:00
|
|
|
class Model {
|
|
|
|
constructor(values) {
|
|
|
|
this.__originalValues = {};
|
|
|
|
|
|
|
|
if (values) {
|
|
|
|
this.setValues(values);
|
|
|
|
} else {
|
|
|
|
this.setValues(this.getDefaults());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-21 16:34:43 +02:00
|
|
|
setValues(values, scalarOnly) {
|
2020-04-14 13:13:45 +02:00
|
|
|
if (!values) return;
|
|
|
|
|
|
|
|
for (let key in values) {
|
|
|
|
if (values.hasOwnProperty(key) && key !== "__originalValues") {
|
|
|
|
this[key] = values[key];
|
2020-04-21 16:34:43 +02:00
|
|
|
|
|
|
|
if (typeof values[key] !== "object") {
|
2020-04-14 13:13:45 +02:00
|
|
|
this.__originalValues[key] = values[key];
|
2020-04-21 16:34:43 +02:00
|
|
|
} else if (!scalarOnly) {
|
|
|
|
this.__originalValues[key] = JSON.parse(JSON.stringify(values[key]));
|
2020-04-14 13:13:45 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
getValues(changed) {
|
|
|
|
const result = {};
|
|
|
|
const defaults = this.getDefaults();
|
|
|
|
|
|
|
|
for (let key in this.__originalValues) {
|
|
|
|
if (this.__originalValues.hasOwnProperty(key) && key !== "__originalValues") {
|
|
|
|
let val;
|
|
|
|
if (defaults.hasOwnProperty(key)) {
|
|
|
|
switch (typeof defaults[key]) {
|
2020-04-23 14:30:28 +02:00
|
|
|
case "bigint":
|
|
|
|
case "number":
|
|
|
|
val = parseFloat(this[key]);
|
|
|
|
break;
|
|
|
|
case "boolean":
|
|
|
|
val = !!this[key];
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
val = this[key];
|
2020-04-14 13:13:45 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
val = this[key];
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!changed || JSON.stringify(val) !== JSON.stringify(this.__originalValues[key])) {
|
|
|
|
result[key] = val;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
getDefaults() {
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Model;
|