MCPcopy
hub / github.com/miragejs/miragejs / addMethodsToModelClass

Method addMethodsToModelClass

lib/orm/associations/has-many.js:72–307  ·  view source on GitHub ↗

* Registers has-many association defined by given key on given model, * defines getters / setters for associated records and associated records' ids, * adds methods for creating unsaved child records and creating saved ones * * @method addMethodsToModelClass * @param {Function} ModelC

(ModelClass, key)

Source from the content-addressed store, hash-verified

70 * @public
71 */
72 addMethodsToModelClass(ModelClass, key) {
73 let modelPrototype = ModelClass.prototype;
74 let association = this;
75 let foreignKey = this.getForeignKey();
76 let associationHash = { [key]: this };
77
78 modelPrototype.hasManyAssociations = Object.assign(
79 modelPrototype.hasManyAssociations,
80 associationHash
81 );
82
83 // update hasManyAssociationFks
84 Object.keys(modelPrototype.hasManyAssociations).forEach((key) => {
85 const value = modelPrototype.hasManyAssociations[key];
86 modelPrototype.hasManyAssociationFks[value.getForeignKey()] = value;
87 });
88
89 // Add to target's dependent associations array
90 this.schema.addDependentAssociation(this, this.modelName);
91
92 // TODO: look how this is used. Are these necessary, seems like they could be gotten from the above?
93 // Or we could use a single data structure to store this information?
94 modelPrototype.associationKeys.add(key);
95 modelPrototype.associationIdKeys.add(foreignKey);
96
97 Object.defineProperty(modelPrototype, foreignKey, {
98 /*
99 object.childrenIds
100 - returns an array of the associated children's ids
101 */
102 get() {
103 this._tempAssociations = this._tempAssociations || {};
104 let tempChildren = this._tempAssociations[key];
105 let ids = [];
106
107 if (tempChildren) {
108 if (association.isPolymorphic) {
109 ids = tempChildren.models.map((model) => ({
110 type: model.modelName,
111 id: model.id,
112 }));
113 } else {
114 ids = tempChildren.models.map((model) => model.id);
115 }
116 } else {
117 ids = this.attrs[foreignKey] || [];
118 }
119
120 return ids;
121 },
122
123 /*
124 object.childrenIds = ([childrenIds...])
125 - sets the associated children (via id)
126 */
127 set(ids) {
128 let tempChildren;
129

Callers 1

registerModelMethod · 0.45

Calls 10

getForeignKeyMethod · 0.95
capitalizeFunction · 0.90
camelizeFunction · 0.90
newMethod · 0.80
toCollectionNameMethod · 0.80
addMethod · 0.45
createMethod · 0.45
saveMethod · 0.45
reloadMethod · 0.45

Tested by

no test coverage detected