bookshelf.js
10.7 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
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _lodash = require('lodash');
var _helpers = require('./helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _events = require('./base/events');
var _events2 = _interopRequireDefault(_events);
var _model = require('./model');
var _model2 = _interopRequireDefault(_model);
var _collection = require('./collection');
var _collection2 = _interopRequireDefault(_collection);
var _relation2 = require('./relation');
var _relation3 = _interopRequireDefault(_relation2);
var _errors = require('./errors');
var _errors2 = _interopRequireDefault(_errors);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @class Bookshelf
* @classdesc
*
* The Bookshelf library is initialized by passing an initialized Knex client
* instance. The knex documentation provides a number of examples for different
* databases.
*
* @constructor
* @param {Knex} knex Knex instance.
*/
// All core modules required for the bookshelf instance.
function Bookshelf(knex) {
var bookshelf = {
VERSION: require('../package.json').version
};
var Model = bookshelf.Model = _model2.default.extend({
_builder: builderFn,
// The `Model` constructor is referenced as a property on the `Bookshelf`
// instance, mixing in the correct `builder` method, as well as the
// `relation` method, passing in the correct `Model` & `Collection`
// constructors for later reference.
_relation: function _relation(type, Target, options) {
if (type !== 'morphTo' && !(0, _lodash.isFunction)(Target)) {
throw new Error('A valid target model must be defined for the ' + (0, _lodash.result)(this, 'tableName') + ' ' + type + ' relation');
}
return new Relation(type, Target, options);
}
}, {
/**
* @method Model.forge
* @belongsTo Model
* @description
*
* A simple helper function to instantiate a new Model without needing `new`.
*
* @param {Object=} attributes Initial values for this model's attributes.
* @param {Object=} options Hash of options.
* @param {string=} options.tableName Initial value for {@linkcode Model#tableName tableName}.
* @param {boolean=} [options.hasTimestamps=false]
*
* Initial value for {@linkcode Model#hasTimestamps hasTimestamps}.
*
* @param {boolean} [options.parse=false]
*
* Convert attributes by {@linkcode Model#parse parse} before being
* {@linkcode Model#set set} on the `model`.
*/
forge: forge,
/**
* @method Model.collection
* @belongsTo Model
* @description
*
* A simple static helper to instantiate a new {@link Collection}, setting
* the current `model` as the collection's target.
*
* @example
*
* Customer.collection().fetch().then(function(collection) {
* // ...
* });
*
* @param {(Model[])=} models
* @param {Object=} options
* @returns {Collection}
*/
collection: function collection(models, options) {
return new bookshelf.Collection(models || [], (0, _lodash.extend)({}, options, { model: this }));
},
/**
* @method Model.count
* @belongsTo Model
* @since 0.8.2
* @description
*
* Gets the number of matching records in the database, respecting any
* previous calls to {@link Model#query query}. If a `column` is provided,
* records with a null value in that column will be excluded from the count.
*
* @param {string} [column='*']
* Specify a column to count - rows with null values in this column will be excluded.
* @param {Object=} options
* Hash of options.
* @returns {Promise<Number>}
* A promise resolving to the number of matching rows.
*/
count: function count(column, options) {
return this.forge().count(column, options);
},
/**
* @method Model.fetchAll
* @belongsTo Model
* @description
*
* Simple helper function for retrieving all instances of the given model.
*
* @see Model#fetchAll
* @returns {Promise<Collection>}
*/
fetchAll: function fetchAll(options) {
return this.forge().fetchAll(options);
}
});
var Collection = bookshelf.Collection = _collection2.default.extend({
_builder: builderFn
}, {
/**
* @method Collection.forge
* @belongsTo Collection
* @description
*
* A simple helper function to instantiate a new Collection without needing
* new.
*
* @param {(Object[]|Model[])=} [models]
* Set of models (or attribute hashes) with which to initialize the
* collection.
* @param {Object} options Hash of options.
*
* @example
*
* var Promise = require('bluebird');
* var Accounts = bookshelf.Collection.extend({
* model: Account
* });
*
* var accounts = Accounts.forge([
* {name: 'Person1'},
* {name: 'Person2'}
* ]);
*
* Promise.all(accounts.invokeMap('save')).then(function() {
* // collection models should now be saved...
* });
*/
forge: forge
});
// The collection also references the correct `Model`, specified above, for
// creating new `Model` instances in the collection.
Collection.prototype.model = Model;
Model.prototype.Collection = Collection;
var Relation = _relation3.default.extend({
Model: Model, Collection: Collection
});
// A `Bookshelf` instance may be used as a top-level pub-sub bus, as it mixes
// in the `Events` object. It also contains the version number, and a
// `Transaction` method referencing the correct version of `knex` passed into
// the object.
(0, _lodash.extend)(bookshelf, _events2.default, _errors2.default, {
/**
* @method Bookshelf#transaction
* @memberOf Bookshelf
* @description
*
* An alias to `{@link http://knexjs.org/#Transactions
* Knex#transaction}`, the `transaction` object must be passed along in the
* options of any relevant Bookshelf calls, to ensure all queries are on the
* same connection. The entire transaction block is a promise that will
* resolve when the transaction is committed, or fail if the transaction is
* rolled back.
*
* var Promise = require('bluebird');
*
* Bookshelf.transaction(function(t) {
* return new Library({name: 'Old Books'})
* .save(null, {transacting: t})
* .tap(function(model) {
* return Promise.map([
* {title: 'Canterbury Tales'},
* {title: 'Moby Dick'},
* {title: 'Hamlet'}
* ], function(info) {
* // Some validation could take place here.
* return new Book(info).save({'shelf_id': model.id}, {transacting: t});
* });
* });
* }).then(function(library) {
* console.log(library.related('books').pluck('title'));
* }).catch(function(err) {
* console.error(err);
* });
*
* @param {Bookshelf~transactionCallback} transactionCallback
* Callback containing transaction logic. The callback should return a
* promise.
*
* @returns {Promise<mixed>}
* A promise resolving to the value returned from {@link
* Bookshelf~transactionCallback transactionCallback}.
*/
transaction: function transaction() {
return this.knex.transaction.apply(this, arguments);
},
/**
* @callback Bookshelf~transactionCallback
* @description
*
* A transaction block to be provided to {@link Bookshelf#transaction}.
*
* @see {@link http://knexjs.org/#Transactions Knex#transaction}
* @see Bookshelf#transaction
*
* @param {Transaction} transaction
* @returns {Promise<mixed>}
*/
// Provides a nice, tested, standardized way of adding plugins to a
// `Bookshelf` instance, injecting the current instance into the plugin,
// which should be a module.exports.
plugin: function plugin(_plugin, options) {
var _this = this;
if ((0, _lodash.isString)(_plugin)) {
try {
require('./plugins/' + _plugin)(this, options);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
if (!process.browser) {
require(_plugin)(this, options);
}
}
} else if ((0, _lodash.isArray)(_plugin)) {
(0, _lodash.each)(_plugin, function (p) {
_this.plugin(p, options);
});
} else {
_plugin(this, options);
}
return this;
}
});
/**
* @member Bookshelf#knex
* @memberOf Bookshelf
* @type {Knex}
* @description
* A reference to the {@link http://knexjs.org Knex.js} instance being used by Bookshelf.
*/
bookshelf.knex = knex;
// The `forge` function properly instantiates a new Model or Collection
// without needing the `new` operator... to make object creation cleaner
// and more chainable.
function forge() {
return new (Function.prototype.bind.apply(this, [null].concat(Array.prototype.slice.call(arguments))))();
}
function builderFn(tableNameOrBuilder) {
var _this2 = this;
var builder = null;
if ((0, _lodash.isString)(tableNameOrBuilder)) {
builder = bookshelf.knex(tableNameOrBuilder);
} else if (tableNameOrBuilder == null) {
builder = bookshelf.knex.queryBuilder();
} else {
// Assuming here that `tableNameOrBuilder` is a QueryBuilder instance. Not
// aware of a way to check that this is the case (ie. using
// `Knex.isQueryBuilder` or equivalent).
builder = tableNameOrBuilder;
}
return builder.on('query', function (data) {
return _this2.trigger('query', data);
});
}
// Attach `where`, `query`, and `fetchAll` as static methods.
['where', 'query'].forEach(function (method) {
Model[method] = Collection[method] = function () {
var model = this.forge();
return model[method].apply(model, arguments);
};
});
return bookshelf;
}
// Constructor for a new `Bookshelf` object, it accepts an active `knex`
// instance and initializes the appropriate `Model` and `Collection`
// constructors for use in the current instance.
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
Bookshelf.initialize = function (knex) {
_helpers2.default.warn("Bookshelf.initialize is deprecated, pass knex directly: require('bookshelf')(knex)");
return new Bookshelf(knex);
};
// Finally, export `Bookshelf` to the world.
exports.default = Bookshelf;