-
Notifications
You must be signed in to change notification settings - Fork 0
/
entity.js
74 lines (61 loc) · 2.01 KB
/
entity.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
'use strict';
const assert = require('assert');
const NamedObjectMap = require('./named_object_map');
const Serializable = require('./serializable');
const { identical } = require('./mappers');
const Category = require('./category');
const FormValue = require('./form_value');
class Entity extends Serializable {
get formValuesMap() {
return NamedObjectMap.fromArray(
[...this.retrieveAttachableFormsMap().values()].map((form) => {
return new FormValue(form, this.document[form.name] || false);
})
);
}
retrieveAttachableFormsMap(onlyMissing = false) {
return NamedObjectMap.fromArray(this.category.forms.filter(form => {
if (onlyMissing && Object.hasOwnProperty.call(this.document, form.name)) {
return false;
}
return form.isAttachable(this.document);
}));
}
_assign(document) {
const availableFormsMap = this.retrieveAttachableFormsMap(true);
const updatedForms = [];
for (const form of availableFormsMap.values()) {
if (Object.hasOwnProperty.call(document, form.name)) {
const formValue = new FormValue(form, document[form.name]);
if (!formValue.isValid) {
console.error(formValue);
throw new Error('invalid form value');
}
this.document[form.name] = formValue.value;
updatedForms.push(form);
}
}
return updatedForms;
}
updateDocument(document) {
this.document = {};
let allUpdatedForms = [];
let updatedForms = [];
while ((updatedForms = this._assign(document)).length > 0) {
allUpdatedForms = allUpdatedForms.concat(updatedForms);
}
Object.freeze(this.document);
return allUpdatedForms;
}
normalize() {
const document = this.document;
return this.updateDocument(document);
}
}
Entity.primaryKey = '_id';
Entity.property('document', identical);
Entity.reference('category', Category);
Entity.property('_id', identical);
Entity.property('number', identical);
Entity.property('metadata', identical);
module.exports = Entity;