-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.js
262 lines (205 loc) · 10 KB
/
model.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import util from 'util';
import chalk from 'ansi-colors';
import Inflector from 'i';
import { classify, underscore } from 'ember-cli-string-utils';
import { primaryKeyTypeSafetyCheck, generateUUID } from './utils';
const { singularize, pluralize } = Inflector();
const targetNamespace = typeof global === 'object' ? global : window;
export default function(options) {
return Object.assign({}, {
modelName: null,
primaryKey: null,
defaultAttributes: {},
attributes: [],
count() {
const models = Array.from(targetNamespace.MemServer.DB[this.modelName] || []);
return models.length;
},
find(param) {
if (!param) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.find(id) cannot be called without a valid id`));
} else if (Array.isArray(param)) {
const models = Array.from(targetNamespace.MemServer.DB[this.modelName] || []);
return models.reduce((result, model) => {
const foundModel = param.includes(model.id) ? model : null;
return foundModel ? result.concat([foundModel]) : result;
}, []);
} else if (typeof param !== 'number') {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.find(id) cannot be called without a valid id`));
}
const models = Array.from(targetNamespace.MemServer.DB[this.modelName] || []);
return models.find((model) => model.id === param);
},
findBy(options) {
if (!options) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.findBy(id) cannot be called without a parameter`));
}
const keys = Object.keys(options);
const models = targetNamespace.MemServer.DB[this.modelName] || [];
return models.find((model) => comparison(model, options, keys, 0));
},
findAll(options={}) {
const models = Array.from(targetNamespace.MemServer.DB[this.modelName] || []);
const keys = Object.keys(options);
if (keys.length === 0) {
return models;
}
return models.filter((model) => comparison(model, options, keys, 0));
},
insert(options) {
const models = targetNamespace.MemServer.DB[this.modelName] || [];
if (models.length === 0) {
const recordsPrimaryKey = this.primaryKey || (options.uuid ? 'uuid' : 'id');
this.primaryKey = recordsPrimaryKey;
this.attributes.push(this.primaryKey);
}
const defaultAttributes = this.attributes.reduce((result, attribute) => {
if (attribute === this.primaryKey) {
result[attribute] = this.primaryKey === 'id' ? incrementId(this) : generateUUID();
return result;
}
const target = this.defaultAttributes[attribute];
result[attribute] = typeof target === 'function' ? target() : target;
return result;
}, {});
const target = Object.assign(defaultAttributes, options);
primaryKeyTypeSafetyCheck(this.primaryKey, target[this.primaryKey], this.modelName);
const existingRecord = target.id ? this.find(target.id) : this.findBy({ uuid: target.uuid });
if (existingRecord) {
throw new Error(chalk.red(`[MemServer] ${this.modelName} ${this.primaryKey} ${target[this.primaryKey]} already exists in the database! ${this.modelName}.insert(${util.inspect(options)}) fails`));
}
Object.keys(target)
.filter((attribute) => !this.attributes.includes(attribute))
.forEach((attribute) => this.attributes.push(attribute));
models.push(target);
return target;
},
update(record) {
if (!record || (!record.id && !record.uuid)) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.update(record) requires id or uuid primary key to update a record`));
}
const targetRecord = record.id ? this.find(record.id) : this.findBy({ uuid: record.uuid });
if (!targetRecord) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.update(record) failed because ${this.modelName} with ${this.primaryKey}: ${record[this.primaryKey]} does not exist`));
}
const recordsUnknownAttribute = Object.keys(record)
.find((attribute) => !this.attributes.includes(attribute));
if (recordsUnknownAttribute) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.update ${this.primaryKey}: ${record[this.primaryKey]} fails, ${this.modelName} model does not have ${recordsUnknownAttribute} attribute to update`));
}
return Object.assign(targetRecord, record);
},
delete(record) {
const models = targetNamespace.MemServer.DB[this.modelName] || [];
if (models.length === 0) {
throw new Error(chalk.red(`[MemServer] ${this.modelName} has no records in the database to delete. ${this.modelName}.delete(${util.inspect(record)}) failed`));
} else if (!record) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.delete(model) model object parameter required to delete a model`));
}
const targetRecord = record.id ? this.find(record.id) : this.findBy({ uuid: record.uuid });
if (!targetRecord) {
throw new Error(chalk.red(`[MemServer] Could not find ${this.modelName} with ${this.primaryKey} ${record[this.primaryKey]} to delete. ${this.modelName}.delete(${util.inspect(record)}) failed`));
}
const targetIndex = models.indexOf(targetRecord);
targetNamespace.MemServer.DB[this.modelName].splice(targetIndex, 1);
return targetRecord;
},
embed(relationship) { // EXAMPLE: { comments: Comment }
if (typeof relationship !== 'object' || relationship.modelName) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.embed(relationshipObject) requires an object as a parameter: { relationshipKey: $RelationshipModel }`));
}
const key = Object.keys(relationship)[0];
if (!relationship[key]) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.embed() fails: ${key} Model reference is not a valid. Please put a valid $ModelName to ${this.modelName}.embed()`));
}
return Object.assign(this.embedReferences, relationship);
},
embedReferences: {},
serializer(objectOrArray) {
if (!objectOrArray) {
return;
} else if (Array.isArray(objectOrArray)) {
return objectOrArray.map((object) => this.serialize(object), []);
}
return this.serialize(objectOrArray);
},
serialize(object) { // NOTE: add links object ?
if (Array.isArray(object)) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.serialize(object) expects an object not an array. Use ${this.modelName}.serializer(data) for serializing array of records`));
}
const objectWithAllAttributes = this.attributes.reduce((result, attribute) => {
if (result[attribute] === undefined) {
result[attribute] = null;
}
return result;
}, Object.assign({}, object));
return Object.keys(this.embedReferences).reduce((result, embedKey) => {
const embedModel = this.embedReferences[embedKey];
const embeddedRecords = this.getRelationship(object, embedKey, embedModel);
return Object.assign({}, result, { [embedKey]: embedModel.serializer(embeddedRecords) });
}, objectWithAllAttributes);
},
getRelationship(parentObject, relationshipName, relationshipModel) {
if (Array.isArray(parentObject)) {
throw new Error(chalk.red(`[MemServer] ${this.modelName}.getRelationship expects model input to be an object not an array`));
}
const targetRelationshipModel = relationshipModel ||
targetNamespace.MemServer.Models[classify(singularize(relationshipName))];
const hasManyRelationship = pluralize(relationshipName) === relationshipName;
if (!targetRelationshipModel) {
throw new Error(chalk.red(`[MemServer] ${relationshipName} relationship could not be found on ${this.modelName} model. Please put the ${relationshipName} Model object as the third parameter to ${this.modelName}.getRelationship function`));
} else if (hasManyRelationship) {
if (parentObject.id) {
const hasManyIDRecords = targetRelationshipModel.findAll({
[`${underscore(this.modelName)}_id`]: parentObject.id
});
return hasManyIDRecords.length > 0 ? hasManyIDRecords : [];
} else if (parentObject.uuid) {
const hasManyUUIDRecords = targetRelationshipModel.findAll({
[`${underscore(this.modelName)}_uuid`]: parentObject.uuid
});
return hasManyUUIDRecords.length > 0 ? hasManyUUIDRecords : [];
}
}
const objectRef = parentObject[`${underscore(relationshipName)}_id`] ||
parentObject[`${underscore(relationshipName)}_uuid`] ||
parentObject[`${underscore(targetRelationshipModel.modelName)}_id`] ||
parentObject[`${underscore(targetRelationshipModel.modelName)}_uuid`];
if (objectRef && (typeof objectRef === 'number')) {
return targetRelationshipModel.find(objectRef) ;
} else if (objectRef) {
return targetRelationshipModel.findBy({ uuid: objectRef });
}
if (parentObject.id) {
return targetRelationshipModel.findBy({
[`${underscore(this.modelName)}_id`]: parentObject.id
});
} else if (parentObject.uuid) {
return targetRelationshipModel.findBy({
[`${underscore(this.modelName)}_uuid`]: parentObject.uuid
});
}
}
}, options);
}
function incrementId(Model) {
const ids = targetNamespace.MemServer.DB[Model.modelName];
if (ids.length === 0) {
return 1;
}
const lastIdInSequence = ids
.map((model) => model.id)
.sort((a, b) => a - b)
.find((id, index, array) => index === array.length - 1 ? true : id + 1 !== array[index + 1]);
return lastIdInSequence + 1;
}
// NOTE: if records were ordered by ID, then there could be performance benefit
function comparison(model, options, keys, index=0) {
const key = keys[index];
if (keys.length === index) {
return model[key] === options[key];
} else if (model[key] === options[key]) {
return comparison(model, options, keys, index + 1);
}
return false;
}