/
index.js
415 lines (355 loc) · 11.3 KB
/
index.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/*
* Geddy JavaScript Web development framework
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
Example model file, would be app/models/user.js:
var User = function () {
this.property('login', 'string', {required: true});
this.property('password', 'string', {required: true});
this.property('lastName', 'string');
this.property('firstName', 'string');
this.validatesPresent('login');
this.validatesFormat('login', /[a-z]+/, {message: 'Subdivisions!'});
this.validatesLength('login', {min: 3});
this.validatesConfirmed('password', 'confirmPassword');
this.validatesWithFunction('password',
function (s) { return s.length > 0; // Could be anything
});
};
User.prototype.someMethod = function () {
// Do some stuff on a User instance
};
User = geddy.model.register('User', User);
*/
var model = {}
, utils = require('../utils');
model.datatypes = require('./datatypes.js');
model.validators = require('./validators.js');
model.formatters = require('./formatters.js');
utils.mixin(model, new (function () {
var _createModelItemConstructor = function (def) {
// Base constructor function for all model items
var ModelItemConstructor = function (params) {
this.type = def.name;
// Items fetched from an API should have this flag set to true
this.saved = params.saved || false;
// If fetched and instantiated from an API-call, give the
// instance the appropriate ID -- newly created objects won't
// have one until saved
if (params.saved) {
this.id = params.id;
}
this.isValid = function () {
return !this.errors;
};
// Callback should be in the format of function (err, result) {}
this.save = function () {
var args = Array.prototype.slice.call(arguments)
, arg
, opts
, callback;
while ((arg = args.shift())) {
if (typeof arg == 'function') {
callback = arg;
}
else {
opts = arg;
}
}
if (this.errors) {
callback(this.errors, null);
}
else {
if (model.useTimestamps && this.saved) {
this.updatedAt = new Date();
}
model.adapter[this.type].save(this, opts, callback);
}
};
this.updateAttributes = function () {
var args = Array.prototype.slice.call(arguments)
, params = args.unshift()
, arg
, opts
, callback;
while ((arg = args.shift())) {
if (typeof arg == 'function') {
callback = arg;
}
else {
opts = arg;
}
}
geddy.model.updateItem(this, params);
if (opts.remote) {
this.save(opts, callback);
}
};
this.toString = function () {
var obj = {};
obj.id = this.id;
obj.type = this.type;
var props = this.properties;
var formatter;
for (var p in props) {
formatter = model.formatters[props[p].datatype];
obj[p] = typeof formatter == 'function' ? formatter(this[p]) : this[p];
}
return JSON.stringify(obj);
};
this.toJson = this.toString;
};
return ModelItemConstructor;
};
var _createStaticMethodsMixin = function (name) {
var obj = {}
, createAPIMethod = function (method) {
return function () {
if (!model.adapter) {
throw new Error('geddy.model.adapter is not defined.');
}
return model.adapter[name][method].apply(model.adapter,
arguments);
};
};
obj.create = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(name);
return model.createItem.apply(model, args);
};
// Create statics that invoke the same model-name/method
// combination on the model.adapter, e.g.:
// FooBar.load => geddy.model.adapter.FooBar.load
['load', 'update', 'remove', 'save'].forEach(function (method) {
obj[method] = createAPIMethod(method);
});
return obj;
};
this.adapter = null;
this.descriptionRegistry = {};
this.useTimestamps = false;
this.forceCamel = true;
this.register = function (name, ModelDefinition) {
var origProto = ModelDefinition.prototype
, defined
, ModelCtor;
// Create the place to store the metadata about the model structure
// to use to do validations, etc. when constructing
model.descriptionRegistry[name] = new model.ModelDescription(name);
// Execute all the definition methods to create that metadata
ModelDefinition.prototype = new model.ModelDefinitionBase(name);
defined = new ModelDefinition();
// Create the constructor function to use when calling static
// ModelCtor.create. Gives them the proper instanceof value,
// and .valid, etc. instance-methods.
ModelCtor = _createModelItemConstructor(defined);
// Mix in the static methods like .create and .load
utils.mixin(ModelCtor, _createStaticMethodsMixin(name));
// Same with statics
utils.mixin(ModelCtor, defined);
// Mix any functions defined directly in the model-item definition
// 'constructor' into the original prototype, and set it as the prototype of the
// actual constructor
utils.mixin(origProto, defined);
ModelCtor.prototype = origProto;
model[name] = ModelCtor;
return ModelCtor;
};
this.createItem = function (name, params) {
var item = new model[name](params);
item = this.validateAndUpdateFromParams(item, params);
if (this.useTimestamps && !item.createdAt) {
item.createdAt = new Date();
}
// After-create hook
if (typeof item.afterCreate == 'function') {
item.afterCreate();
}
return item;
};
this.updateItem = function (item, params) {
item = this.validateAndUpdateFromParams(item, params);
// After-update hook
if (typeof item.afterUpdate == 'function') {
item.afterUpdate();
}
return item;
};
this.validateAndUpdateFromParams = function (item, passedParams) {
var params
, type = model.descriptionRegistry[item.type]
, properties = type.properties
, validated = null
, errs = null
, val
// May be revalidating, clear errors
delete item.errors;
if (this.forceCamel) {
params = {};
for (var p in passedParams) {
params[geddy.string.camelize(p)] = passedParams[p];
}
}
else {
params = passedParams;
}
// User-input should never contain these -- but we still want
// to validate them
if (typeof item.createdAt != 'undefined') {
params.createdAt = item.createdAt;
}
if (typeof item.updatedAt != 'undefined') {
params.updatedAt = item.updatedAt;
}
for (var p in properties) {
validated = this.validateProperty(properties[p], params);
// If there are any failed validations, the errs param
// contains an Object literal keyed by field name, and the
// error message for the first failed validation for that
// property
if (validated.err) {
errs = errs || {};
errs[p] = validated.err;
}
// Otherwise add this property the the return item
else {
item[p] = validated.val;
}
}
// Should never be incuded in user input
delete params.createdAt;
delete params.updatedAt;
if (errs) {
item.errors = errs;
}
return item;
};
this.validateProperty = function (prop, params) {
var name = prop.name
, val = params[name]
, result;
// Validate for the base datatype only if there actually is a value --
// e.g., undefined will fail the validation for Number, even if the
// field is optional
if (val) {
if (prop.datatype == '*') {
result = {
val: val
};
}
else {
result = model.datatypes[prop.datatype.toLowerCase()](prop.name, val);
if (result.err) {
return {
err: result.err,
val: null
};
}
}
// Value may have been modified in the datatype check -- e.g.,
// 'false' changed to false, '8.0' changed to 8, '2112' changed to
// 2112, etc.
val = result.val;
}
// Now go through all the base validations for this property
var validations = prop.validations;
var validator;
var err;
for (var p in validations) {
validator = model.validators[p]
if (typeof validator != 'function') {
throw new Error(p + ' is not a valid validator');
}
err = validator(name, val, params, validations[p]);
// If there's an error for a validation, don't bother
// trying to continue with more validations -- just return
// this first error message
if (err) {
return {
err: err,
val: null
};
}
}
// If there weren't any errors, return the value for this property
// and no error
return {
err: null,
val: val
};
};
})());
model.ModelDefinitionBase = function (name) {
var self = this
, _getValidator = function (p) {
return function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(p);
return self.validates.apply(self, args);
};
};
this.name = name;
this.property = function (name, datatype, o) {
model.descriptionRegistry[this.name].properties[name] =
new model.PropertyDescription(name, datatype, o);
};
this.defineProperties = function (obj) {
for (var property in obj) {
this.property(property, obj[property].type, obj);
}
}
this.validates = function (condition, name, qualifier, opts) {
var rule = utils.mixin({}, opts, true);
rule.qualifier = qualifier;
model.descriptionRegistry[this.name].properties[name]
.validations[condition] = rule;
};
// For each of the validators, create a validatesFooBar from
// validates('fooBar' ...
for (var p in model.validators) {
this['validates' + utils.string.capitalize(p)] = _getValidator(p);
}
// Add the base model properties -- these should not be handled by user input
if (model.useTimestamps) {
this.property('createdAt', 'datetime');
this.property('updatedAt', 'datetime');
}
};
model.ModelDescription = function (name) {
this.name = name;
this.properties = {};
};
model.PropertyDescription = function (name, datatype, o) {
var opts = o || {};
this.name = name;
this.datatype = datatype;
this.options = opts;
var validations = {};
for (var p in opts) {
if (opts.required || opts.length) {
validations.present = true;
}
if (opts.length) {
validations.length = opts.length;
}
if (opts.format) {
validations.format = opts.format;
}
}
this.validations = validations;
};
module.exports = model;