@depup/bookshelf 1.2.0-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,995 @@
1
+ // Base Model
2
+ // ---------------
3
+ 'use strict';
4
+
5
+ const _ = require('lodash');
6
+ const inherits = require('util').inherits;
7
+ const Events = require('./events');
8
+ const constants = require('../constants');
9
+
10
+ /**
11
+ * @class
12
+ * @classdesc
13
+ * @extends Events
14
+ * @inheritdoc
15
+ * @description
16
+ *
17
+ * The "ModelBase" is similar to the 'Active Model' in Rails, it defines a
18
+ * standard interface from which other objects may inherit.
19
+ */
20
+ function ModelBase(attributes, options) {
21
+ let attrs = attributes || {};
22
+ options = options || {};
23
+ this.attributes = Object.create(null);
24
+ this._previousAttributes = {};
25
+ this._reset();
26
+ this.relations = {};
27
+ this.cid = _.uniqueId('c');
28
+
29
+ if (options.parse) attrs = this.parse(attrs, options) || {};
30
+ if (options.visible) this.visible = _.clone(options.visible);
31
+ if (options.hidden) this.hidden = _.clone(options.hidden);
32
+ if (typeof options.requireFetch === 'boolean') this.requireFetch = options.requireFetch;
33
+ if (options.tableName) this.tableName = options.tableName;
34
+ if (typeof options.hasTimestamps === 'boolean' || Array.isArray(options.hasTimestamps)) {
35
+ this.hasTimestamps = options.hasTimestamps;
36
+ }
37
+
38
+ this.set(attrs, options);
39
+ this.initialize.apply(this, arguments);
40
+ }
41
+
42
+ /**
43
+ * Registers an event listener.
44
+ *
45
+ * @method ModelBase#on
46
+ * @example
47
+ * customer.on('fetching', function(model) {
48
+ * // Do something before the data is fetched from the database
49
+ * })
50
+ * @see Events#on
51
+ */
52
+
53
+ /**
54
+ * @method ModelBase#off
55
+ * @example
56
+ *
57
+ * customer.off('fetched fetching');
58
+ * ship.off(); // This will remove all event listeners
59
+ *
60
+ * @see Events#off
61
+ */
62
+
63
+ /**
64
+ * @method ModelBase#trigger
65
+ * @example
66
+ *
67
+ * ship.trigger('fetched');
68
+ *
69
+ * @see Events#trigger
70
+ */
71
+ inherits(ModelBase, Events);
72
+
73
+ /**
74
+ * @method ModelBase#initialize
75
+ * @description
76
+ *
77
+ * Called by the {@link Model Model constructor} when creating a new instance.
78
+ * Override this function to add custom initialization, such as event listeners.
79
+ * Because plugins may override this method in subclasses, make sure to call
80
+ * your super (extended) class. e.g.
81
+ *
82
+ * initialize: function() {
83
+ * this.constructor.__super__.initialize.apply(this, arguments);
84
+ * // Your initialization code ...
85
+ * }
86
+ *
87
+ * @see Model
88
+ *
89
+ * @param {Object} attributes
90
+ * Initial values for this model's attributes.
91
+ * @param {Object=} options
92
+ * The hash of options passed to {@link Model constructor}.
93
+ */
94
+ ModelBase.prototype.initialize = function() {};
95
+
96
+ /**
97
+ * @name ModelBase#tableName
98
+ * @member {string}
99
+ * @description
100
+ *
101
+ * A required property for any database usage, The
102
+ * {@linkcode Model#tableName tableName} property refers to the database
103
+ * table name the model will query against.
104
+ *
105
+ * @example
106
+ *
107
+ * var Television = bookshelf.model('Television', {
108
+ * tableName: 'televisions'
109
+ * });
110
+ */
111
+
112
+ /**
113
+ * A special property of models which represents their unique identifier, named by the
114
+ * {@link Model#idAttribute idAttribute}. If you set the `id` in the attributes hash,
115
+ * it will be copied onto the model as a direct property.
116
+ *
117
+ * Models can be retrieved by their id from collections, and the id is used when fetching
118
+ * models and building model relations.
119
+ *
120
+ * Note that a model's `id` property can always be accessed even when the value of its
121
+ * {@link Model#idAttribute idAttribute} is not `'id'`.
122
+ *
123
+ * @member {(number|string)}
124
+ * @example
125
+ * const Television = bookshelf.model('Television', {
126
+ * tableName: 'televisions',
127
+ * idAttribute: 'coolId'
128
+ * })
129
+ *
130
+ * new Television({coolId: 1}).fetch(tv => {
131
+ * tv.get('coolId') // 1
132
+ * tv.id // 1
133
+ * })
134
+ */
135
+ ModelBase.prototype.id;
136
+
137
+ /**
138
+ * @member {string}
139
+ * @default "id"
140
+ * @description
141
+ *
142
+ * This tells the model which attribute to expect as the unique identifier
143
+ * for each database row (typically an auto-incrementing primary key named
144
+ * `'id'`). Note that if you are using {@link Model#parse parse} and {@link
145
+ * Model#format format} (to have your model's attributes in `camelCase`,
146
+ * but your database's columns in `snake_case`, for example) this refers to
147
+ * the name returned by parse (`myId`), not the actual database column
148
+ * (`my_id`).
149
+ *
150
+ * You can also get the parsed id attribute value by using the model's
151
+ * {@link Model#parsedIdAttribute parsedIdAttribute} method.
152
+ *
153
+ * If the table you're working with does not have a Primary-Key in the form
154
+ * of a single column you'll have to override it with a getter that returns
155
+ * `null`. Overriding with `undefined` does not cascade the default behavior of
156
+ * the value `'id'`. Such a getter in ES6 would look like
157
+ * `get idAttribute() { return null }`.
158
+ */
159
+ ModelBase.prototype.idAttribute = 'id';
160
+
161
+ /**
162
+ * @member {Object|Null}
163
+ * @default null
164
+ * @description
165
+ *
166
+ * This can be used to define any default values for attributes that are not
167
+ * present when creating or updating a model in a {@link Model#save save} call.
168
+ * The default behavior is to *not* use these default values on updates unless
169
+ * the `defaults: true` option is passed to the {@link Model#save save} call.
170
+ * For inserts the default values will always be used if present.
171
+ *
172
+ * @example
173
+ *
174
+ * var MyModel = bookshelf.model('MyModel', {
175
+ * defaults: {property1: 'foo', property2: 'bar'},
176
+ * tableName: 'my_models'
177
+ * })
178
+ *
179
+ * MyModel.forge({property1: 'blah'}).save().then(function(model) {
180
+ * // {property1: 'blah', property2: 'bar'}
181
+ * })
182
+ */
183
+ ModelBase.prototype.defaults = null;
184
+
185
+ /**
186
+ * Allows defining the default behavior when there are no results when fetching a model from the
187
+ * database. This applies only when fetching a single model using {@link Model#fetch fetch} or
188
+ * {@link Collection#fetchOne}.
189
+ *
190
+ * You can override this model option when fetching by passing the `{require: false}` or
191
+ * `{require: true}` option to any of the fetch methods mentioned above.
192
+ *
193
+ * @type {boolean}
194
+ * @default true
195
+ * @since 1.0.0
196
+ * @example
197
+ *
198
+ * // Default behavior
199
+ * const MyModel = bookshelf.model('MyModel', {
200
+ * tableName: 'my_models'
201
+ * })
202
+ *
203
+ * new MyModel({id: 1}).fetch().catch(error => {
204
+ * // Will throw NotFoundError if there are no results
205
+ * })
206
+ *
207
+ * // Overriding the default behavior
208
+ * const MyModel = bookshelf.model('MyModel', {
209
+ * requireFetch: false,
210
+ * tableName: 'my_models'
211
+ * })
212
+ *
213
+ * new MyModel({id: 1}).fetch(model => {
214
+ * // model will be null if there are no results
215
+ })
216
+ */
217
+ ModelBase.prototype.requireFetch = true;
218
+
219
+ /**
220
+ * @member {Boolean|Array}
221
+ * @default false
222
+ * @description
223
+ *
224
+ * Automatically sets the current date and time on the timestamp attributes
225
+ * `created_at` and `updated_at` based on the type of save method. The *update*
226
+ * method will only update `updated_at`, while the *insert* method will set
227
+ * both values.
228
+ *
229
+ * To override the default attribute names, assign an array to this property.
230
+ * The first element will be the *created* column name and the second will be
231
+ * the *updated* one. If any of these elements is set to `null` that particular
232
+ * timestamp attribute will not be used in the model. For example, to
233
+ * automatically update only the `created_at` attribute set this property to
234
+ * `['created_at', null]`.
235
+ *
236
+ * You can override the timestamp attribute values of a model and those values
237
+ * will be used instead of the automatic ones when saving.
238
+ *
239
+ * @example
240
+ *
241
+ * var MyModel = bookshelf.model('MyModel', {
242
+ * hasTimestamps: true,
243
+ * tableName: 'my_models'
244
+ * })
245
+ *
246
+ * var myModel = MyModel.forge({name: 'blah'}).save().then(function(savedModel) {
247
+ * // {
248
+ * // name: 'blah',
249
+ * // created_at: 'Sun Mar 25 2018 15:07:11 GMT+0100 (WEST)',
250
+ * // updated_at: 'Sun Mar 25 2018 15:07:11 GMT+0100 (WEST)'
251
+ * // }
252
+ * })
253
+ *
254
+ * myModel.save({created_at: new Date(2015, 5, 2)}).then(function(updatedModel) {
255
+ * // {
256
+ * // name: 'blah',
257
+ * // created_at: 'Tue Jun 02 2015 00:00:00 GMT+0100 (WEST)',
258
+ * // updated_at: 'Sun Mar 25 2018 15:07:11 GMT+0100 (WEST)'
259
+ * // }
260
+ * })
261
+ */
262
+ ModelBase.prototype.hasTimestamps = false;
263
+
264
+ /**
265
+ * @member {null|Array}
266
+ * @default null
267
+ * @description
268
+ *
269
+ * List of model attributes to exclude from the output when serializing it. This works as a
270
+ * blacklist, and all attributes not present in this list will be shown when calling
271
+ * {@link Model#toJSON toJSON}.
272
+ *
273
+ * By default this is `null` which means that no attributes will be excluded from the output.
274
+ *
275
+ * You can override this list by passing the `{hidden: ['list']}` option directly to the
276
+ * {@link Model#toJSON toJSON} or {@link Model#serialize serialize} call.
277
+ *
278
+ * If both the `hidden` and the {@link Model#visible visible} model properties are set, the
279
+ * `hidden` list will take precedence.
280
+ *
281
+ * @example
282
+ * const MyModel = bookshelf.model('MyModel', {
283
+ * tableName: 'my_models',
284
+ * hidden: ['password']
285
+ * })
286
+ *
287
+ * const myModel = MyModel.forge({
288
+ * name: 'blah',
289
+ * password: 'secure'
290
+ * }).save().then(function(savedModel) {
291
+ * console.log(savedModel.toJSON())
292
+ * // {
293
+ * // name: 'blah',
294
+ * // created_at: 'Sun Mar 25 2018 15:07:11 GMT+0100 (WEST)',
295
+ * // updated_at: 'Sun Mar 25 2018 15:07:11 GMT+0100 (WEST)'
296
+ * // }
297
+ * })
298
+ */
299
+ ModelBase.prototype.hidden = null;
300
+
301
+ /**
302
+ * @member {null|Array}
303
+ * @default null
304
+ * @description
305
+ *
306
+ * List of model attributes to include in the output when serializing it. This works as a
307
+ * whitelist, and all attributes not present in this list will be hidden when calling
308
+ * {@link Model#toJSON toJSON}.
309
+ *
310
+ * By default this is `null` which means that all attributes will be included in the output.
311
+ *
312
+ * You can override this list by passing the `{visible: ['list']}` option directly to the
313
+ * {@link Model#toJSON toJSON} or {@link Model#serialize serialize} call.
314
+ *
315
+ * If both the {@link Model#hidden hidden} and the `visible` model properties are set, the
316
+ * `hidden` list will take precedence.
317
+ *
318
+ * @example
319
+ * const MyModel = bookshelf.model('MyModel', {
320
+ * tableName: 'my_models',
321
+ * visible: ['name', 'created_at']
322
+ * })
323
+ *
324
+ * const myModel = MyModel.forge({
325
+ * name: 'blah',
326
+ * password: 'secure'
327
+ * }).save().then(function(savedModel) {
328
+ * console.log(savedModel.toJSON())
329
+ * // {
330
+ * // name: 'blah',
331
+ * // created_at: 'Sun Mar 25 2018 15:07:11 GMT+0100 (WEST)',
332
+ * // }
333
+ * })
334
+ */
335
+ ModelBase.prototype.visible = null;
336
+
337
+ /**
338
+ * @method
339
+ * @private
340
+ * @description
341
+ *
342
+ * Converts the timestamp keys to actual Date objects. This will not run if the
343
+ * model doesn't have {@link Model#hasTimestamps hasTimestamps} set to either
344
+ * `true` or an array of key names.
345
+ * This method is run internally when reading data from the database to ensure
346
+ * data consistency between the several database implementations.
347
+ * It returns the model instance that called it, so it allows chaining of other
348
+ * model methods.
349
+ *
350
+ * @returns {Model} The model that called this.
351
+ */
352
+ ModelBase.prototype.formatTimestamps = function formatTimestamps() {
353
+ if (!this.hasTimestamps) return this;
354
+
355
+ this.getTimestampKeys().forEach((key) => {
356
+ if (this.get(key)) this.set(key, new Date(this.get(key)));
357
+ });
358
+
359
+ return this;
360
+ };
361
+
362
+ /**
363
+ * @method
364
+ * @description Get the current value of an attribute from the model.
365
+ * @example note.get("title");
366
+ *
367
+ * @param {string} attribute - The name of the attribute to retrieve.
368
+ * @returns {mixed} Attribute value.
369
+ */
370
+ ModelBase.prototype.get = function(attr) {
371
+ return this.attributes[attr];
372
+ };
373
+
374
+ /**
375
+ * @method
376
+ * @private
377
+ * @description
378
+ *
379
+ * Returns the model's {@link Model#idAttribute idAttribute} after applying the
380
+ * model's {@link Model#parse parse} method to it. Doesn't mutate the original
381
+ * value of {@link Model#idAttribute idAttribute} in any way.
382
+ *
383
+ * @example
384
+ *
385
+ * var Customer = bookshelf.model('Customer', {
386
+ * idAttribute: 'id',
387
+ * parse: function(attrs) {
388
+ * return _.mapKeys(attrs, function(value, key) {
389
+ * return 'parsed_' + key;
390
+ * });
391
+ * }
392
+ * });
393
+ *
394
+ * customer.parsedIdAttribute() // 'parsed_id'
395
+ *
396
+ * @returns {mixed} Whatever value the parse method returns.
397
+ */
398
+ ModelBase.prototype.parsedIdAttribute = function() {
399
+ var parsedAttributes = this.parse({[this.idAttribute]: null});
400
+ return parsedAttributes && Object.keys(parsedAttributes)[0];
401
+ };
402
+
403
+ /**
404
+ * @method
405
+ * @description Set a hash of attributes (one or many) on the model.
406
+ * @example
407
+ *
408
+ * customer.set({first_name: "Joe", last_name: "Customer"});
409
+ * customer.set("telephone", "555-555-1212");
410
+ *
411
+ * @param {string|Object} attribute Attribute name, or hash of attribute names and values.
412
+ * @param {mixed=} value If a string was provided for `attribute`, the value to be set.
413
+ * @param {Object=} options
414
+ * @param {Object} [options.unset=false] Remove attributes from the model instead of setting them.
415
+ * @returns {Model} This model.
416
+ */
417
+ ModelBase.prototype.set = function(key, val, options) {
418
+ if (key == null) return this;
419
+ let attrs;
420
+
421
+ // Handle both `"key", value` and `{key: value}` -style arguments.
422
+ if (typeof key === 'object') {
423
+ attrs = key;
424
+ options = val;
425
+ } else {
426
+ (attrs = {})[key] = val;
427
+ }
428
+ options = _.clone(options) || {};
429
+
430
+ // Extract attributes and options.
431
+ const unset = options.unset;
432
+ const current = this.attributes;
433
+ const prev = this.previousAttributes();
434
+
435
+ // Check for changes of `id`.
436
+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
437
+ else if (this.parsedIdAttribute() in attrs) this.id = attrs[this.parsedIdAttribute()];
438
+
439
+ // For each `set` attribute, update or delete the current value.
440
+ for (const attr in attrs) {
441
+ val = attrs[attr];
442
+ if (!_.isEqual(prev[attr], val)) {
443
+ this.changed[attr] = val;
444
+ } else {
445
+ delete this.changed[attr];
446
+ }
447
+ if (unset) {
448
+ delete current[attr];
449
+ } else {
450
+ current[attr] = val;
451
+ }
452
+ }
453
+ return this;
454
+ };
455
+
456
+ /**
457
+ * @method
458
+ * @description
459
+ *
460
+ * Checks for the existence of an id to determine whether the model is
461
+ * considered "new".
462
+ *
463
+ * @example
464
+ *
465
+ * var modelA = new bookshelf.Model();
466
+ * modelA.isNew(); // true
467
+ *
468
+ * var modelB = new bookshelf.Model({id: 1});
469
+ * modelB.isNew(); // false
470
+ */
471
+ ModelBase.prototype.isNew = function() {
472
+ return this.id == null;
473
+ };
474
+
475
+ /**
476
+ * Return a copy of the model's {@link Model#attributes attributes} for JSON
477
+ * stringification. If the {@link Model model} has any relations defined, this
478
+ * will also call {@link Model#toJSON toJSON} on each of the related
479
+ * objects, and include them on the object unless `{shallow: true}` is
480
+ * passed as an option.
481
+ *
482
+ * You can define a whitelist of model attributes to include on the ouput with
483
+ * the `{visible: ['list', 'of', 'attributes']}` option. The `{hidden: []}`
484
+ * option produces the opposite effect, hiding attributes from the output.
485
+ *
486
+ * This method is called internally by {@link Model#toJSON toJSON}. Override
487
+ * this function if you want to customize its output.
488
+ *
489
+ * @example
490
+ * var artist = new bookshelf.Model({
491
+ * firstName: "Wassily",
492
+ * lastName: "Kandinsky"
493
+ * });
494
+ *
495
+ * artist.set({birthday: "December 16, 1866"});
496
+ *
497
+ * console.log(JSON.stringify(artist));
498
+ * // {firstName: "Wassily", lastName: "Kandinsky", birthday: "December 16, 1866"}
499
+ *
500
+ * @param {Object} [options]
501
+ * @param {Boolean} [options.shallow=false] Whether to exclude relations from the output or not.
502
+ * @param {Boolean} [options.omitPivot=false]
503
+ * Whether to exclude pivot values from the output or not.
504
+ * @param {Array} [options.hidden] List of model attributes to exclude from the output.
505
+ * @param {Array} [options.visible]
506
+ List of model attributes to include on the output. All other attributes will be hidden.
507
+ * @param {Boolean} [options.visibility=true]
508
+ * Whether to use visibility options or not. If set to `false` the `hidden` and `visible` options
509
+ * will be ignored.
510
+ * @returns {Object} Serialized model as a plain object.
511
+ */
512
+ ModelBase.prototype.serialize = function(options) {
513
+ if (typeof options !== 'object' || options === null) options = {};
514
+ if (options.visibility === null || options.visibility === undefined) options.visibility = true;
515
+
516
+ if (options.omitNew && this.isNew()) return null;
517
+
518
+ let attributes = Object.assign({}, this.attributes);
519
+
520
+ if (options.shallow !== true) {
521
+ let relations = _.mapValues(this.relations, (relation) => (relation.toJSON ? relation.toJSON(options) : relation));
522
+ relations = _.omitBy(relations, _.isNull);
523
+
524
+ const pivot = this.pivot && !options.omitPivot && this.pivot.attributes;
525
+ const pivotAttributes = _.mapKeys(pivot, (value, key) => `${constants.PIVOT_PREFIX}${key}`);
526
+
527
+ attributes = Object.assign(attributes, relations, pivotAttributes);
528
+ }
529
+
530
+ if (options.visibility) {
531
+ const visible = options.visible || this.visible;
532
+ const hidden = options.hidden || this.hidden;
533
+
534
+ if (visible) attributes = _.pick(attributes, visible);
535
+ if (hidden) attributes = _.omit(attributes, hidden);
536
+ }
537
+
538
+ return attributes;
539
+ };
540
+
541
+ /**
542
+ * @method
543
+ * @description
544
+ *
545
+ * Called automatically by {@link
546
+ * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior
547
+ * `JSON.stringify`}. To customize serialization, override {@link
548
+ * Model#serialize serialize}.
549
+ *
550
+ * @param {Object=} options Options passed to {@link Model#serialize}.
551
+ */
552
+ ModelBase.prototype.toJSON = function(options) {
553
+ return this.serialize(options);
554
+ };
555
+
556
+ /**
557
+ * @method
558
+ * @private
559
+ * @returns String representation of the object.
560
+ */
561
+ ModelBase.prototype.toString = function() {
562
+ return '[Object Model]';
563
+ };
564
+
565
+ /**
566
+ * @method
567
+ * @description Get the HTML-escaped value of an attribute.
568
+ * @param {string} attribute The attribute to escape.
569
+ * @returns {string} HTML-escaped value of an attribute.
570
+ */
571
+ ModelBase.prototype.escape = function(key) {
572
+ return _.escape(this.get(key));
573
+ };
574
+
575
+ /**
576
+ * @method
577
+ * @description
578
+ * Returns `true` if the attribute contains a value that is not null or undefined.
579
+ * @param {string} attribute The attribute to check.
580
+ * @returns {Boolean} True if `attribute` is set, otherwise `false`.
581
+ */
582
+ ModelBase.prototype.has = function(attr) {
583
+ return this.get(attr) != null;
584
+ };
585
+
586
+ /**
587
+ * @method
588
+ * @description
589
+ *
590
+ * The `parse` method is called whenever a {@link Model model}'s data is
591
+ * returned in a {@link Model#fetch fetch} call. The function is passed the raw
592
+ * database response object, and should return the {@link Model#attributes
593
+ * attributes} hash to be {@link Model#set set} on the model. The default
594
+ * implementation is a no-op, simply passing through the JSON response.
595
+ * Override this if you need to format the database responses - for example
596
+ * calling {@link
597
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
598
+ * JSON.parse} on a text field containing JSON, or explicitly typecasting a
599
+ * boolean in a sqlite3 database response.
600
+ *
601
+ * If you need to format your data before it is saved to the database, override
602
+ * the {@link Model#format format} method in your models. That method does the
603
+ * opposite operation of `parse`.
604
+ *
605
+ * @example
606
+ * // Example of a parser to convert snake_case to camelCase, using lodash
607
+ * // This is just an example. You can use the official case converter plugin
608
+ * // to achieve the same functionality.
609
+ * model.parse = function(attrs) {
610
+ * return _.mapKeys(attrs, function(value, key) {
611
+ * return _.camelCase(key);
612
+ * });
613
+ * };
614
+ *
615
+ * @param {Object} attributes Hash of attributes to parse.
616
+ * @returns {Object} Parsed attributes.
617
+ */
618
+ ModelBase.prototype.parse = _.identity;
619
+
620
+ /**
621
+ * @method
622
+ * @description
623
+ *
624
+ * Remove an attribute from the model. `unset` is a noop if the attribute
625
+ * doesn't exist.
626
+ *
627
+ * Note that unsetting an attribute from the model will not affect the related
628
+ * record's column value when saving the model. In order to clear the value of a
629
+ * column in the database record, set the attribute value to `null` instead:
630
+ * `model.set("column_name", null)`.
631
+ *
632
+ * @param attribute Attribute to unset.
633
+ * @returns {Model} This model.
634
+ */
635
+ ModelBase.prototype.unset = function(attr, options) {
636
+ return this.set(attr, void 0, _.extend({}, options, {unset: true}));
637
+ };
638
+
639
+ /**
640
+ * @method
641
+ * @description Clear all attributes on the model.
642
+ * @returns {Model} This model.
643
+ */
644
+ ModelBase.prototype.clear = function(options) {
645
+ const undefinedKeys = _.mapValues(this.attributes, () => undefined);
646
+ return this.set(undefinedKeys, Object.assign({}, options, {unset: true}));
647
+ };
648
+
649
+ /**
650
+ * @method
651
+ * @description
652
+ *
653
+ * The `format` method is used to modify the current state of the model before
654
+ * it is persisted to the database. The `attributes` passed are a shallow clone
655
+ * of the {@link Model model}, and are only used for inserting/updating - the
656
+ * current values of the model are left intact.
657
+ *
658
+ * Do note that `format` is used to modify the state of the model when
659
+ * accessing the database, so if you remove an attribute in your `format`
660
+ * method, that attribute will never be persisted to the database, but it will
661
+ * also never be used when doing a `fetch()`, which may cause unexpected
662
+ * results. You should be very cautious with implementations of this method
663
+ * that may remove the primary key from the list of attributes.
664
+ *
665
+ * If you need to modify the database data before it is given to the model,
666
+ * override the {@link Model#parse parse} method instead. That method does the
667
+ * opposite operation of `format`.
668
+ *
669
+ * @param {Object} attributes The attributes to be converted.
670
+ * @returns {Object} Formatted attributes.
671
+ */
672
+ ModelBase.prototype.format = _.identity;
673
+
674
+ /**
675
+ * This method returns a specified relation loaded on the relations hash on the model, or calls the associated relation
676
+ * method and adds it to the relations hash if one exists and has not yet been loaded.
677
+ *
678
+ * @example
679
+ * new Photo({id: 1}).fetch({
680
+ * withRelated: ['account']
681
+ * }).then(function(photo) {
682
+ * var account = photo.related('account') // Get the eagerly loaded account
683
+ *
684
+ * if (account.id) {
685
+ * // Fetch a relation that has not been eager loaded yet
686
+ * return account.related('trips').fetch()
687
+ * }
688
+ * })
689
+ *
690
+ * @param {string} name The name of the relation to retrieve.
691
+ * @returns {Model|Collection|undefined}
692
+ * The specified relation as defined by a method on the model, or `undefined` if it does not exist.
693
+ */
694
+ ModelBase.prototype.related = function(name) {
695
+ return this.relations[name] || (this[name] ? (this.relations[name] = this[name]()) : void 0);
696
+ };
697
+
698
+ /**
699
+ * @method
700
+ * @description
701
+ * Returns a new instance of the model with identical {@link
702
+ * Model#attributes attributes}, including any relations from the cloned
703
+ * model.
704
+ *
705
+ * @returns {Model} Cloned instance of this model.
706
+ */
707
+ ModelBase.prototype.clone = function() {
708
+ const model = new this.constructor(this.attributes);
709
+ Object.assign(
710
+ model.relations,
711
+ _.mapValues(this.relations, (r) => r.clone())
712
+ );
713
+ model._previousAttributes = _.clone(this._previousAttributes);
714
+ model.changed = _.clone(this.changed);
715
+ return model;
716
+ };
717
+
718
+ /**
719
+ * @method
720
+ * @private
721
+ * @description
722
+ *
723
+ * Returns the method that will be used on save, either 'update' or 'insert'.
724
+ * This is an internal helper that uses `isNew` and `options.method` to
725
+ * determine the correct method. If `option.method` is provided, it will be
726
+ * returned, but lowercased for later comparison.
727
+ *
728
+ * @returns {string} Either `'insert'` or `'update'`.
729
+ */
730
+ ModelBase.prototype.saveMethod = function(options) {
731
+ if (!options) options = {};
732
+
733
+ if (options.patch) {
734
+ if (options.method === 'insert')
735
+ throw new TypeError(`Cannot accept incompatible options: method=insert, patch=${options.patch}`);
736
+
737
+ options.method = 'update';
738
+ }
739
+ return ((options.patch && 'update') || options.method) == null
740
+ ? this.isNew()
741
+ ? 'insert'
742
+ : 'update'
743
+ : options.method.toLowerCase();
744
+ };
745
+
746
+ /**
747
+ * @method
748
+ * @private
749
+ * @description
750
+ *
751
+ * Returns the automatic timestamp key names set on this model. Note that this
752
+ * will always return a value even if the model has {@link Model#hasTimestamps
753
+ * hasTimestamps} set to `false`. In this case and when set to `true` the
754
+ * return value will be the default names of `created_at` and `updated_at`.
755
+ *
756
+ * @returns {Array<string>} The two timestamp key names.
757
+ */
758
+ ModelBase.prototype.getTimestampKeys = function() {
759
+ return Array.isArray(this.hasTimestamps) ? this.hasTimestamps : constants.DEFAULT_TIMESTAMP_KEYS;
760
+ };
761
+
762
+ /**
763
+ * @method
764
+ * @description
765
+ * Automatically sets the timestamp attributes on the model, if
766
+ * {@link Model#hasTimestamps hasTimestamps} is set to `true` or an array. It
767
+ * checks if the model is new and sets the `created_at` and `updated_at`
768
+ * attributes (or any other custom attribute names you have set) to the current
769
+ * date. If the model is not new and is just being updated then only the
770
+ * `updated_at` attribute gets automatically updated.
771
+ *
772
+ * If the model contains any user defined `created_at` or `updated_at` values,
773
+ * there won't be any automatic updated of these attributes and the user
774
+ * supplied values will be used instead.
775
+ *
776
+ * @param {Object=} options
777
+ * @param {string} [options.method]
778
+ * Either `'insert'` or `'update'` to specify what kind of save the attribute
779
+ * update is for.
780
+ * @param {string} [options.date]
781
+ * Either a Date object or ms since the epoch. Specify what date is used for
782
+ * updateing the timestamps, i.e. if something other than `new Date()` should be used.
783
+ * @returns {Object} A hash of timestamp attributes that were set.
784
+ */
785
+ ModelBase.prototype.timestamp = function(options) {
786
+ if (!this.hasTimestamps) return {};
787
+
788
+ const now = (options || {}).date ? new Date(options.date) : new Date();
789
+ const attributes = {};
790
+ const method = this.saveMethod(options);
791
+ const timestampKeys = this.getTimestampKeys();
792
+ const createdAtKey = timestampKeys[0];
793
+ const updatedAtKey = timestampKeys[1];
794
+ const isNewModel = method === 'insert';
795
+
796
+ if (updatedAtKey && (isNewModel || this.hasChanged()) && !this.hasChanged(updatedAtKey)) {
797
+ attributes[updatedAtKey] = now;
798
+ }
799
+
800
+ if (createdAtKey && isNewModel && !this.hasChanged(createdAtKey)) {
801
+ attributes[createdAtKey] = now;
802
+ }
803
+
804
+ this.set(attributes, _.extend(options, {silent: true}));
805
+
806
+ return attributes;
807
+ };
808
+
809
+ /**
810
+ * @method
811
+ * @description
812
+ *
813
+ * Returns `true` if any {@link Model#attributes attribute} has changed since
814
+ * the last {@link Model#fetch fetch} or {@link Model#save save}. If an
815
+ * attribute name is passed as argument, returns `true` only if that specific
816
+ * attribute has changed.
817
+ *
818
+ * Note that even if an attribute is changed by using the {@link Model#set set}
819
+ * method, but the new value is exactly the same as the existing one, the
820
+ * attribute is not considered *changed*.
821
+ *
822
+ * @example
823
+ * Author.forge({id: 1}).fetch().then(function(author) {
824
+ * author.hasChanged() // false
825
+ * author.set('name', 'Bob')
826
+ * author.hasChanged('name') // true
827
+ * })
828
+ *
829
+ * @param {string=} attribute A specific attribute to check for changes.
830
+ * @returns {Boolean}
831
+ * `true` if any attribute has changed, `false` otherwise. Alternatively, if
832
+ * the `attribute` argument was specified, checks if that particular
833
+ * attribute has changed.
834
+ */
835
+ ModelBase.prototype.hasChanged = function(attr) {
836
+ if (attr == null) return !_.isEmpty(this.changed);
837
+ return _.has(this.changed, attr);
838
+ };
839
+
840
+ /**
841
+ * @method
842
+ * @description
843
+ *
844
+ * Returns the value of an attribute like it was before the last change. A
845
+ * change is usually done with the {@link Model#set set} method, but it can
846
+ * also be done with the {@link Model#save save} method. This is useful for
847
+ * getting back the original attribute value after it's been changed. It can
848
+ * also be used to get the original value after a model has been saved to the
849
+ * database or destroyed.
850
+ *
851
+ * In case you want to get the previous value of all attributes at once you
852
+ * should use the {@link Model#previousAttributes previousAttributes} method.
853
+ *
854
+ * Note that this will return `undefined` if the model hasn't been fetched,
855
+ * saved, destroyed or eager loaded. However, in case one of these operations
856
+ * did take place, it will return the current value if an attribute hasn't
857
+ * changed. If you want to check if an attribute has changed see the
858
+ * {@link Model#hasChanged hasChanged} method.
859
+ *
860
+ * @example
861
+ * Author.forge({id: 1}).fetch().then(function(author) {
862
+ * author.get('name') // Alice
863
+ * author.set('name', 'Bob')
864
+ * author.previous('name') // 'Alice'
865
+ * })
866
+ *
867
+ * @param {string} attribute The attribute to check.
868
+ * @returns {mixed} The previous value.
869
+ */
870
+ ModelBase.prototype.previous = function(attribute) {
871
+ return this._previousAttributes[attribute];
872
+ };
873
+
874
+ /**
875
+ * @method
876
+ * @description
877
+ *
878
+ * Returns a copy of the {@link Model model}'s attributes like they were before
879
+ * the last change. A change is usually done with the {@link Model#set set}
880
+ * method, but it can also be done with the {@link Model#save save} method.
881
+ * This is mostly useful for getting a diff of the model's attributes after
882
+ * changing some of them. It can also be used to get the previous state of a
883
+ * model after it has been saved to the database or destroyed.
884
+ *
885
+ * In case you want to get the previous value of a single attribute you should
886
+ * use the {@link Model#previous previous} method.
887
+ *
888
+ * Note that this will return an empty object if no changes have been made to
889
+ * the model and it hasn't been fetched, saved or eager loaded.
890
+ *
891
+ * @example
892
+ * Author.forge({id: 1}).fetch().then(function(author) {
893
+ * author.get('name') // Alice
894
+ * author.set('name', 'Bob')
895
+ * author.previousAttributes() // {id: 1, name: 'Alice'}
896
+ * })
897
+ *
898
+ * Author.forge({id: 1}).fetch().then(function(author) {
899
+ * author.get('name') // Alice
900
+ * return author.save({name: 'Bob'})
901
+ * }).then(function(author) {
902
+ * author.get('name') // Bob
903
+ * author.previousAttributes() // {id: 1, name: 'Alice'}
904
+ * })
905
+ *
906
+ * @returns {Object}
907
+ * The attributes as they were before the last change, or an empty object in
908
+ * case the model data hasn't been fetched yet.
909
+ */
910
+ ModelBase.prototype.previousAttributes = function() {
911
+ return _.clone(this._previousAttributes) || {};
912
+ };
913
+
914
+ /**
915
+ * @method
916
+ * @private
917
+ * @description
918
+ *
919
+ * Resets the `changed` hash for the model. Typically called after a `sync`
920
+ * action (save, fetch, destroy).
921
+ *
922
+ * @returns {Model} This model.
923
+ */
924
+ ModelBase.prototype._reset = function() {
925
+ this.changed = Object.create(null);
926
+ return this;
927
+ };
928
+
929
+ /**
930
+ * @method ModelBase#pick
931
+ * @see http://lodash.com/docs/#pick
932
+ */
933
+ /**
934
+ * @method ModelBase#omit
935
+ * @see http://lodash.com/docs/#omit
936
+ */
937
+ // "_" methods that we want to implement on the Model.
938
+ const modelMethods = ['pick', 'omit'];
939
+
940
+ // Mix in each "_" method as a proxy to `Model#attributes`.
941
+ _.each(modelMethods, function(method) {
942
+ ModelBase.prototype[method] = function() {
943
+ return _[method].apply(_, [this.attributes].concat(Array.from(arguments)));
944
+ };
945
+ });
946
+
947
+ /**
948
+ * This static method allows you to create your own Model classes by extending {@link Model bookshelf.Model}.
949
+ *
950
+ * It correctly sets up the prototype chain, which means that subclasses created this way can be further extended and
951
+ * subclassed as far as you need.
952
+ *
953
+ * @example
954
+ * const Promise = require('bluebird')
955
+ * const compare = require('some-crypt-library')
956
+ *
957
+ * const Customer = bookshelf.model('Customer', {
958
+ * initialize() {
959
+ * this.constructor.__super__.initialize.apply(this, arguments)
960
+ *
961
+ * // Setting up a listener for the 'saving' event
962
+ * this.on('saving', this.validateSave)
963
+ * },
964
+ *
965
+ * validateSave() {
966
+ * return doValidation(this.attributes)
967
+ * },
968
+ *
969
+ * account() {
970
+ * // Defining a relation with the Account model
971
+ * return this.belongsTo(Account)
972
+ * }
973
+ * }, {
974
+ * login: Promise.method(function(email, password) {
975
+ * if (!email || !password)
976
+ * throw new Error('Email and password are both required')
977
+ *
978
+ * return new this({email: email.toLowerCase()})
979
+ * .fetch()
980
+ * .tap(function(customer) {
981
+ * if (!compare(password, customer.get('password'))
982
+ * throw new Error('Invalid password')
983
+ * })
984
+ * })
985
+ * })
986
+ *
987
+ * @method Model.extend
988
+ * @param {Object} [prototypeProperties] Instance methods and properties to be attached to instances of the new class.
989
+ * @param {Object} [classProperties]
990
+ * Class (i.e. static) functions and properties to be attached to the constructor of the new class.
991
+ * @returns {Function} Constructor for new Model subclass.
992
+ */
993
+ ModelBase.extend = require('../extend');
994
+
995
+ module.exports = ModelBase;