model.js
21.2 KB
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
'use strict';
var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
var _inherits = require('inherits');
var _inherits2 = _interopRequireDefault(_inherits);
var _events = require('./events');
var _events2 = _interopRequireDefault(_events);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var PIVOT_PREFIX = '_pivot_'; // Base Model
// ---------------
var DEFAULT_TIMESTAMP_KEYS = ['created_at', 'updated_at'];
// List of attributes attached directly from the `options` passed to the constructor.
var modelProps = ['tableName', 'hasTimestamps'];
/**
* @class
* @classdesc
* @extends Events
* @inheritdoc
* @description
*
* The "ModelBase" is similar to the 'Active Model' in Rails, it defines a
* standard interface from which other objects may inherit.
*/
function ModelBase(attributes, options) {
var attrs = attributes || {};
options = options || {};
this.attributes = Object.create(null);
this._reset();
this.relations = {};
this.cid = _lodash2.default.uniqueId('c');
if (options) {
_lodash2.default.extend(this, _lodash2.default.pick(options, modelProps));
if (options.parse) attrs = this.parse(attrs, options) || {};
}
this.set(attrs, options);
this.initialize.apply(this, arguments);
}
/**
* @method ModelBase#on
* @example
*
* customer.on('fetching', function(model, columns) {
* // Do something before the data is fetched from the database
* });
*
* @see Events#on
*/
/**
* @method ModelBase#off
* @example
*
* customer.off('fetched fetching');
* ship.off(); // This will remove all event listeners
*
* @see Events#off
*/
/**
* @method ModelBase#trigger
* @example
*
* ship.trigger('fetched');
*
* @see Events#trigger
*/
(0, _inherits2.default)(ModelBase, _events2.default);
/**
* @method ModelBase#initialize
* @description
*
* Called by the {@link Model Model constructor} when creating a new instance.
* Override this function to add custom initialization, such as event listeners.
*
* @see Model
*
* @param {Object} attributes
* Initial values for this model's attributes.
* @param {Object=} options
* The hash of options passed to {@link Model constructor}.
*/
ModelBase.prototype.initialize = function () {};
/**
* @name ModelBase#tableName
* @member {string}
* @description
*
* A required property for any database usage, The
* {@linkcode Model#tableName tableName} property refers to the database
* table name the model will query against.
*
* @example
*
* var Television = bookshelf.Model.extend({
* tableName: 'televisions'
* });
*/
/**
* @member {string}
* @default "id"
* @description
*
* This tells the model which attribute to expect as the unique identifier
* for each database row (typically an auto-incrementing primary key named
* `"id"`). Note that if you are using {@link Model#parse parse} and {@link
* Model#format format} (to have your model's attributes in `camelCase`,
* but your database's columns in `snake_case`, for example) this refers to
* the name returned by parse (`myId`), not the database column (`my_id`).
*
*/
ModelBase.prototype.idAttribute = 'id';
/**
* @member {boolean|Array}
* @default false
* @description
*
* Sets the current date/time on the timestamps columns `created_at` and
* `updated_at` for a given method. The 'update' method will only update
* `updated_at`. To override the default column names, assign an array
* to {@link Model#hasTimestamps hasTimestamps}. The first element will
* be the created column name and the second will be the updated
* column name.
*
*/
ModelBase.prototype.hasTimestamps = false;
/**
* @method
* @description Get the current value of an attribute from the model.
* @example note.get("title");
*
* @param {string} attribute - The name of the attribute to retrieve.
* @returns {mixed} Attribute value.
*/
ModelBase.prototype.get = function (attr) {
return this.attributes[attr];
};
/**
* @method
* @description Set a hash of attributes (one or many) on the model.
* @example
*
* customer.set({first_name: "Joe", last_name: "Customer"});
* customer.set("telephone", "555-555-1212");
*
* @param {string|Object} attribute Attribute name, or hash of attribute names and values.
* @param {mixed=} value If a string was provided for `attribute`, the value to be set.
* @param {Object=} options
* @param {Object} [options.unset=false] Remove attributes from the model instead of setting them.
* @returns {Model} This model.
*/
ModelBase.prototype.set = function (key, val, options) {
if (key == null) return this;
var attrs = void 0;
// Handle both `"key", value` and `{key: value}` -style arguments.
if ((typeof key === 'undefined' ? 'undefined' : (0, _typeof3.default)(key)) === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options = (0, _lodash.clone)(options) || {};
// Extract attributes and options.
var unset = options.unset;
var current = this.attributes;
var prev = this._previousAttributes;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// For each `set` attribute, update or delete the current value.
for (var attr in attrs) {
val = attrs[attr];
if (!_lodash2.default.isEqual(prev[attr], val)) {
this.changed[attr] = val;
} else {
delete this.changed[attr];
}
if (unset) {
delete current[attr];
} else {
current[attr] = val;
}
}
return this;
};
/**
* @method
* @description
*
* Checks for the existence of an id to determine whether the model is
* considered "new".
*
* @example
*
* var modelA = new bookshelf.Model();
* modelA.isNew(); // true
*
* var modelB = new bookshelf.Model({id: 1});
* modelB.isNew(); // false
*/
ModelBase.prototype.isNew = function () {
return this.id == null;
};
/**
* @method
* @description
*
* Return a copy of the model's {@link Model#attributes attributes} for JSON
* stringification. If the {@link Model model} has any relations defined, this
* will also call {@link Model#toJSON toJSON} on each of the related
* objects, and include them on the object unless `{shallow: true}` is
* passed as an option.
*
* `serialize` is called internally by {@link Model#toJSON toJSON}. Override
* this function if you want to customize its output.
*
* @example
* var artist = new bookshelf.Model({
* firstName: "Wassily",
* lastName: "Kandinsky"
* });
*
* artist.set({birthday: "December 16, 1866"});
*
* console.log(JSON.stringify(artist));
* // {firstName: "Wassily", lastName: "Kandinsky", birthday: "December 16, 1866"}
*
* @param {Object=} options
* @param {bool} [options.shallow=false] Exclude relations.
* @param {bool} [options.omitPivot=false] Exclude pivot values.
* @returns {Object} Serialized model as a plain object.
*/
ModelBase.prototype.serialize = function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var _options$shallow = options.shallow,
shallow = _options$shallow === undefined ? false : _options$shallow,
_options$omitPivot = options.omitPivot,
omitPivot = _options$omitPivot === undefined ? false : _options$omitPivot,
_options$omitNew = options.omitNew,
omitNew = _options$omitNew === undefined ? false : _options$omitNew;
var attributes = this.attributes;
if (omitNew && this.isNew()) {
return null;
}
if (!shallow) {
var relations = (0, _lodash.mapValues)(this.relations, function (relation, key) {
return relation.toJSON != null ? relation.toJSON(options) : relation;
});
// Omit null relations from the omitNew option
relations = _lodash2.default.omitBy(relations, _lodash2.default.isNull);
var pivot = this.pivot && !omitPivot && this.pivot.attributes;
var pivotAttributes = (0, _lodash.mapKeys)(pivot, function (value, key) {
return '' + PIVOT_PREFIX + key;
});
return (0, _extends3.default)({}, attributes, relations, pivotAttributes);
}
return (0, _extends3.default)({}, attributes);
};
/**
* @method
* @description
*
* Called automatically by {@link
* https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior
* `JSON.stringify`}. To customize serialization, override {@link
* Model#serialize serialize}.
*
* @param {Object=} options Options passed to {@link Model#serialize}.
*/
ModelBase.prototype.toJSON = function (options) {
return this.serialize(options);
};
/**
* @method
* @private
* @returns String representation of the object.
*/
ModelBase.prototype.toString = function () {
return '[Object Model]';
};
/**
* @method
* @description Get the HTML-escaped value of an attribute.
* @param {string} attribute The attribute to escape.
* @returns {string} HTML-escaped value of an attribute.
*/
ModelBase.prototype.escape = function (key) {
return _lodash2.default.escape(this.get(key));
};
/**
* @method
* @description
* Returns `true` if the attribute contains a value that is not null or undefined.
* @param {string} attribute The attribute to check.
* @returns {bool} True if `attribute` is set, otherwise null.
*/
ModelBase.prototype.has = function (attr) {
return this.get(attr) != null;
};
/**
* @method
* @description
*
* The parse method is called whenever a {@link Model model}'s data is returned
* in a {@link Model#fetch fetch} call. The function is passed the raw database
* response object, and should return the {@link Model#attributes
* attributes} hash to be {@link Model#set set} on the model. The default
* implementation is a no-op, simply passing through the JSON response.
* Override this if you need to format the database responses - for example
* calling {@link
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
* JSON.parse} on a text field containing JSON, or explicitly typecasting a
* boolean in a sqlite3 database response.
*
* @example
*
* // Example of a "parse" to convert snake_case to camelCase, using `underscore.string`
* model.parse = function(attrs) {
* return _.reduce(attrs, function(memo, val, key) {
* memo[_.camelCase(key)] = val;
* return memo;
* }, {});
* };
*
* @param {Object} response Hash of attributes to parse.
* @returns {Object} Parsed attributes.
*/
ModelBase.prototype.parse = _lodash.identity;
/**
* @method
* @description
*
* Remove an attribute from the model. `unset` is a noop if the attribute
* doesn't exist.
*
* Note that unsetting an attribute from the model will not affect the related
* record's column value when saving the model. In order to clear the value of a
* column in the database record, set the attribute value to `null` instead:
* `model.set("column_name", null)`.
*
* @param attribute Attribute to unset.
* @returns {Model} This model.
*/
ModelBase.prototype.unset = function (attr, options) {
return this.set(attr, void 0, _lodash2.default.extend({}, options, { unset: true }));
};
/**
* @method
* @description Clear all attributes on the model.
* @returns {Model} This model.
*/
ModelBase.prototype.clear = function (options) {
var undefinedKeys = (0, _lodash.mapValues)(this.attributes, function () {
return undefined;
});
return this.set(undefinedKeys, (0, _extends3.default)({}, options, { unset: true }));
};
/**
* @method
* @description
*
* The `format` method is used to modify the current state of the model before
* it is persisted to the database. The `attributes` passed are a shallow clone
* of the {@link Model model}, and are only used for inserting/updating - the
* current values of the model are left intact.
*
* @param {Object} attributes The attributes to be converted.
* @returns {Object} Formatted attributes.
*/
ModelBase.prototype.format = _lodash.identity;
/**
* @method
* @description
*
* The `related` method returns a specified relation loaded on the relations
* hash on the model, or calls the associated relation method and adds it to
* the relations hash if one exists and has not yet been loaded.
*
* @example
*
* new Photo({id: 1}).fetch({
* withRelated: ['account']
* }).then(function(photo) {
* if (photo) {
* var account = photo.related('account');
* if (account.id) {
* return account.related('trips').fetch();
* }
* }
* });
*
* @param name {string} The name of the relation to retrieve.
* @returns {Model|Collection|undefined} The specified relation as defined by a
* method on the model, or undefined if it does not exist.
*/
ModelBase.prototype.related = function (name) {
return this.relations[name] || (this[name] ? this.relations[name] = this[name]() : void 0);
};
/**
* @method
* @description
* Returns a new instance of the model with identical {@link
* Model#attributes attributes}, including any relations from the cloned
* model.
*
* @returns {Model} Cloned instance of this model.
*/
ModelBase.prototype.clone = function () {
var model = new this.constructor(this.attributes);
(0, _lodash.assign)(model.relations, (0, _lodash.mapValues)(this.relations, function (r) {
return r.clone();
}));
model._previousAttributes = (0, _lodash.clone)(this._previousAttributes);
model.changed = (0, _lodash.clone)(this.changed);
return model;
};
/**
* @method
* @private
* @description
*
* Returns the method that will be used on save, either 'update' or 'insert'.
* This is an internal helper that uses `isNew` and `options.method` to
* determine the correct method. If `option.method` is provided, it will be
* returned, but lowercased for later comparison.
*
* @returns {string} Either `'insert'` or `'update'`.
*/
ModelBase.prototype.saveMethod = function () {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$method = _ref.method,
method = _ref$method === undefined ? null : _ref$method,
_ref$patch = _ref.patch,
patch = _ref$patch === undefined ? false : _ref$patch;
if (patch) {
if (method == 'insert') throw new TypeError('Cannot accept incompatible options: methods=' + method + ', patch=' + patch);
method = 'update';
}
return (patch && 'update' || method) == null ? this.isNew() ? 'insert' : 'update' : method.toLowerCase();
};
/**
* @method
* @description
* Sets the timestamp attributes on the model, if {@link Model#hasTimestamps
* hasTimestamps} is set to `true` or an array. Check if the model {@link
* Model#isNew isNew} or if `{method: 'insert'}` is provided as an option and
* set the `created_at` and `updated_at` attributes to the current date if it
* is being inserted, and just the `updated_at` attribute if it's being updated.
* This method may be overriden to use different column names or types for the
* timestamps.
*
* @param {Object=} options
* @param {string} [options.method]
* Either `'insert'` or `'update'`. Specify what kind of save the attribute
* update is for.
*
* @returns {Object} A hash of timestamp attributes that were set.
*/
ModelBase.prototype.timestamp = function (options) {
if (!this.hasTimestamps) return {};
var now = new Date();
var attributes = {};
var method = this.saveMethod(options);
var keys = _lodash2.default.isArray(this.hasTimestamps) ? this.hasTimestamps : DEFAULT_TIMESTAMP_KEYS;
var _keys = (0, _slicedToArray3.default)(keys, 2),
createdAtKey = _keys[0],
updatedAtKey = _keys[1];
if (updatedAtKey) {
attributes[updatedAtKey] = this.attributes[updatedAtKey] ? new Date(this.attributes[updatedAtKey]) : now;
}
if (createdAtKey && method === 'insert') {
attributes[createdAtKey] = this.attributes[createdAtKey] ? new Date(this.attributes[createdAtKey]) : now;
}
this.set(attributes, options);
return attributes;
};
/**
* @method
* @description
*
* Returns true if any {@link Model#attributes attribute} attribute has changed
* since the last {@link Model#fetch fetch}, {@link Model#save save}, or {@link
* Model#destroy destroy}. If an attribute is passed, returns true only if that
* specific attribute has changed.
*
* @param {string=} attribute
* @returns {bool}
* `true` if any attribute has changed. Or, if `attribute` was specified, true
* if it has changed.
*/
ModelBase.prototype.hasChanged = function (attr) {
if (attr == null) return !_lodash2.default.isEmpty(this.changed);
return _lodash2.default.has(this.changed, attr);
};
/**
* @method
* @description
*
* Returns the this previous value of a changed {@link Model#attributes
* attribute}, or `undefined` if one had not been specified previously.
*
* @param {string} attribute The attribute to check
* @returns {mixed} The previous value
*/
ModelBase.prototype.previous = function (attribute) {
return this._previousAttributes[attribute];
};
/**
* @method
* @description
*
* Return a copy of the {@link Model model}'s previous attributes from the
* model's last {@link Model#fetch fetch}, {@link Model#save save}, or {@link
* Model#destroy destroy}. Useful for getting a diff between versions of a
* model, or getting back to a valid state after an error occurs.
*
* @returns {Object} The attributes as they were before the last change.
*/
ModelBase.prototype.previousAttributes = function () {
return (0, _lodash.clone)(this._previousAttributes);
};
/**
* @method
* @private
* @description
*
* Resets the `_previousAttributes` and `changed` hash for the model.
* Typically called after a `sync` action (save, fetch, delete) -
*
* @returns {Model} This model.
*/
ModelBase.prototype._reset = function () {
this._previousAttributes = (0, _lodash.clone)(this.attributes);
this.changed = Object.create(null);
return this;
};
/**
* @method ModelBase#keys
* @see http://lodash.com/docs/#keys
*/
/**
* @method ModelBase#values
* @see http://lodash.com/docs/#values
*/
/**
* @method ModelBase#toPairs
* @see http://lodash.com/docs/#toPairs
*/
/**
* @method ModelBase#invert
* @see http://lodash.com/docs/#invert
*/
/**
* @method ModelBase#pick
* @see http://lodash.com/docs/#pick
*/
/**
* @method ModelBase#omit
* @see http://lodash.com/docs/#omit
*/
// "_" methods that we want to implement on the Model.
var modelMethods = ['keys', 'values', 'toPairs', 'invert', 'pick', 'omit'];
// Mix in each "_" method as a proxy to `Model#attributes`.
_lodash2.default.each(modelMethods, function (method) {
ModelBase.prototype[method] = function () {
return _lodash2.default[method].apply(_lodash2.default, [this.attributes].concat(Array.prototype.slice.call(arguments)));
};
});
/**
* @method Model.extend
* @description
*
* To create a Model class of your own, you extend {@link Model bookshelf.Model}.
*
* `extend` correctly sets up the prototype chain, so subclasses created with
* `extend` can be further extended and subclassed as far as you like.
*
* var checkit = require('checkit');
* var Promise = require('bluebird');
* var bcrypt = Promise.promisifyAll(require('bcrypt'));
*
* var Customer = bookshelf.Model.extend({
* initialize: function() {
* this.on('saving', this.validateSave);
* },
*
* validateSave: function() {
* return checkit(rules).run(this.attributes);
* },
*
* account: function() {
* return this.belongsTo(Account);
* },
* }, {
* login: Promise.method(function(email, password) {
* if (!email || !password) throw new Error('Email and password are both required');
* return new this({email: email.toLowerCase().trim()}).fetch({require: true}).tap(function(customer) {
* return bcrypt.compareAsync(password, customer.get('password'))
* .then(function(res) {
* if (!res) throw new Error('Invalid password');
* });
* });
* })
* });
*
* Customer.login(email, password)
* .then(function(customer) {
* res.json(customer.omit('password'));
* }).catch(Customer.NotFoundError, function() {
* res.json(400, {error: email + ' not found'});
* }).catch(function(err) {
* console.error(err);
* });
*
* _Brief aside on `super`: JavaScript does not provide a simple way to call
* `super` — the function of the same name defined higher on the prototype
* chain. If you override a core function like {@link Model#set set}, or {@link
* Model#save save}, and you want to invoke the parent object's implementation,
* you'll have to explicitly call it, along these lines:_
*
* var Customer = bookshelf.Model.extend({
* set: function() {
* // ...
* bookshelf.Model.prototype.set.apply(this, arguments);
* // ...
* }
* });
*
* @param {Object=} prototypeProperties
* Instance methods and properties to be attached to instances of the new
* class.
* @param {Object=} classProperties
* Class (ie. static) functions and properties to be attached to the
* constructor of the new class.
* @returns {Function} Constructor for new `Model` subclass.
*/
ModelBase.extend = require('../extend');
module.exports = ModelBase;