This repository has been archived by the owner on Jun 19, 2021. It is now read-only.
/
driver.js
502 lines (350 loc) · 11.6 KB
/
driver.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
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
/* lib/driver.js */
var app = protos.app;
var _ = require('underscore'),
util = require('util'),
inflect = protos.inflect,
extract = protos.util.extract,
Multi = require('multi'),
slice = Array.prototype.slice;
/**
Driver class. Implements the Model API.
@private
@constructor
@class Driver
*/
function Driver() {
}
/**
Storage instance
@private
@default null
*/
Driver.prototype.storage = null;
/**
Multi support.
@param {object} context
@param {object} config
*/
Driver.prototype.multi = function(config) {
return new Multi(this, config);
}
/**
Provides the Model Hooks to a specific model object
@private
@param {object} context
*/
Driver.prototype.provideTo = function(context) {
// Get ancestor prototype
var proto = this.constructor.prototype,
methodsProto = Driver.prototype.__modelMethods;
// Provide aliases from driver prototype
_.extend(context, methodsProto);
// Provide methods from self
_.extend(context, this.__modelMethods);
// Provide app methods
provideAppMethods.call(this, context, methodsProto);
}
/**
Performs a query with caching capabilities
Cache data can contain the following:
{
cacheID: 'my_cache',
cacheInvalidate: ['other_cache', 'cool_cache'],
cacheTimeout: 3600,
storage: redisStorage
}
By default, the driver's storage will be used, unless
you override it by setting the storage on the cdata object.
@param {object} cdata Cache Data
@param {string} method Driver method to cache
@param {mixed*} various Remaining method parameters
*/
Driver.prototype.queryCached = function() {
var self = this,
params = slice.call(arguments, 0),
cdata = params[0],
method = params[1],
args = params.slice(2),
callback = args.pop();
// Storage can also be passed as part of cdata
var storage = (cdata.storage || this.storage);
var cacheID = cdata.cacheID;
var invalidate = cdata.cacheInvalidate;
var timeout = cdata.cacheTimeout;
var cacheFilter = cdata.cacheFilter;
if (storage) {
if (invalidate) {
if (typeof invalidate == 'string') {
// Invalidate single id
var invalidateID = invalidate;
storage.delete(invalidateID, function(err) {
if (err) callback.call(self, err, null);
else {
if (app.debugLog) app.debug("Invalidated cache for " + invalidateID);
if (cdata.cacheID) {
// Regenerate cache after it has been invalidated
__getSetCacheResults.call(self, {
storage: storage,
cacheID: cacheID,
cacheFilter: cacheFilter,
method: method,
args: args,
callback: callback,
timeout: timeout
});
} else {
// No cacheID, which means the intention was to invalidate. Proceed without further caching
self[method].apply(self, args.concat([callback]));
}
}
});
} else {
// Invalidate multiple id's
var multi = new Multi(storage);
for (var i=0; i < invalidate.length; i++) {
invalidateID = invalidate[i];
invalidate[i] = invalidateID;
multi.delete(invalidateID);
}
multi.exec(function(err, results) {
if (err) callback.call(self, err, null);
else {
if (cdata.cacheID) {
// Regenerate cache after it has been invalidated
if (app.debugLog) app.debug("Invalidated cache for " + invalidate.join(', '));
// Get/Set cache results
__getSetCacheResults.call(self, {
storage: storage,
cacheID: cacheID,
cacheFilter: cacheFilter,
method: method,
args: args,
callback: callback,
timeout: timeout
});
} else {
// No cacheID, which means the intention was to invalidate. Proceed without further caching
self[method].apply(self, args.concat([callback]));
}
}
});
}
} else if (cdata.cacheID) {
// Cache ID Available...
// See if cache is available
__getSetCacheResults.call(this, {
storage: storage,
cacheID: cacheID,
cacheFilter: cacheFilter,
method: method,
args: args,
callback: callback,
timeout: timeout
});
} else {
// No cacheID, proceed without caching
this[method].apply(this, args.concat([callback]));
}
} else {
// No Storage. Warn and proceed without caching
app.log(util.format("%s: not caching since no storage is attached", this.className));
this[method].apply(this, args.concat([callback]));
}
}
/*
Private function in charge of storing the cache and setting timeouts
@private
@param {object} o Params object
@param {int} timeout
*/
function __getSetCacheResults(o) {
var self = this,
storage = o.storage,
cacheID = o.cacheID,
cacheFilter = o.cacheFilter,
method = o.method,
args = o.args,
callback = o.callback,
timeout = o.timeout;
// See if cache is available
storage.get(cacheID, function(err, data) {
if (err) {
callback.call(self, err, null);
} else {
if ( data ) {
// Object found in cache
// Run callback with cached array
var results = JSON.parse(data);
if (app.debugLog) app.debug("Using cached data for " + cacheID);
callback.apply(self, results);
} else {
// Cache new data
self[method].apply(self, args.concat([function(err) {
if (err) {
callback.call(self, err, null);
} else {
// Get results array from arguments
var results = slice.call(arguments, 0);
// Run cache filter if available
if (cacheFilter instanceof Function) {
results = cacheFilter.apply(self, results);
}
// Set cache data
storage.set(cacheID, JSON.stringify(results), function(err) {
if (err) {
callback.call(self, err, null);
} else {
// If timeout available, set expiration
if (timeout && typeof timeout == 'number') {
// Set cache expiration
storage.expire(cacheID, timeout, function(err) {
if (err) callback.call(self, err, null);
else {
// Run callback with results array (after expiration set)
if (app.debugLog) app.debug(util.format("Cached new data for %s (expires in %d seconds)", cacheID, timeout));
callback.apply(self, results);
}
});
} else {
// Run callback with results array
if (app.debugLog) app.debug("Cached new data for " + cacheID);
callback.apply(self, results);
}
}
});
}
}]));
}
}
});
}
/**
**MODEL API**
The Model API methods run in the model context.
The `this` object points to the model instance that
inherited the methods below.
The driver instance attached to the model can be
accessed via `this.driver`.
**IMPLEMENTATION**
Only the empty functions should be implemented in the
drivers. The ones that provide common functionality
& aliases are passed over to the model and integrate
seamlessly with it.
@private
@type object
*/
Driver.prototype.__modelMethods = {
/**
Creates a new model object. Saves into the
database, then creates the model with the provided data.
Validation should be performed against the values in `o`,
throwing an Error if not satisfied.
Provides: [err, model]
@param {object} o
@param {function} callback
*/
new: function(o, callback) {
var self = this;
// Model::insert > Get ID > Create Model
this.insert(o, function(err, id) {
if (err) {
callback.call(self, err, null);
} else {
self.get(id, function(err, model) {
if (err) {
callback.call(self, err, null);
} else {
callback.call(self, null, model);
}
});
}
});
},
/**
Alias of `new`
*/
create: function() { this.new.apply(this, arguments); },
/**
Same behavior as new, but instead of returning a new object,
returns the ID for the new database entry.
Provides: [err, id]
@param {object} o
@param {function} callback
*/
insert: function(o, callback) {},
/**
Alias of `insert`
*/
add: function() { this.insert.apply(this, arguments); },
/**
Gets an new model object.
Type coercion is performed automatically, based on the
type definition settings in the model's `properties`.
The `o` argument can also contain an array of arguments,
which can either be objects or integers. In this case,
an array of models will be provided.
The `fields` argument can receive a list of fields to
retrieve from the database.
Provides: [err, model]
@param {object|int|array} o
@param {array} fields
@param {function} callback
*/
get: function(o, fields, callback) {},
/**
Alias of `get`
*/
find: function() { this.get.apply(this, arguments); },
/**
Saves the model data into the Database.
Since this method is called directly by the `ModelObject`s,
there is no need to validate, since the data provided in `o`
has been properly validated.
The item's ID to update is available on `o.id`.
Provides: [err]
@param {object} o
@param {function} callback
*/
save: function(o, callback) {},
/**
Alias of `save`
*/
update: function() { this.save.apply(this, arguments); },
/**
Deletes the model data from the database.
The `id` argument can also contain an array of id's
to remove from the database.
Provides: [err]
@param {int|array} id
@param {function} callback
@public
*/
delete: function(id, callback) {},
/**
Alias of `delete`
*/
destroy: function() { this.delete.apply(this, arguments); }
}
/*
Provides app methods for model operations
@param {object} model
@param {object} methodsProto
@private
*/
function provideAppMethods(model, methodsProto) {
/*jshint immed:false */
var key, method,
cname = inflect.camelize(model.context),
scname = inflect.singularize(cname),
Application = app.constructor;
for (key in methodsProto) {
var suffix = (key.slice(-3) === 'All') ? cname : scname;
method = key + suffix;
(function(model, key, method) {
app.model[method] = function() {
model[key].apply(model, arguments);
}
}).call(this, model, key, method);
}
}
module.exports = Driver;