-
Notifications
You must be signed in to change notification settings - Fork 4
/
parse-blueprint-options.js
580 lines (447 loc) Β· 27.4 KB
/
parse-blueprint-options.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
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
/**
* Module dependencies
*/
var util = require('util');
var _ = require('@sailshq/lodash');
var flaverr = require('flaverr');
/**
* parseBlueprintOptions()
*
* Parse information from the request for use in a blueprint action.
*
* > This is just the default implementation -- it can be overridden.
* > See http://sailsjs.com/config/blueprints for more information.
*
* | Term | Meaning
* |:----------------------|:----------------------------------------------------------------------------------------|
* | route option | e.g. `model`, `alias`, `parseBlueprintOptions`, `action`, etc. (+ non-standard options)
* | query key | e.g. `criteria`, `newRecord`, `valuesToSet`, `meta`, `using`, etc. (fully standardized)
* | blueprint option | e.g. `criteria`, `newRecord`, `valuesToSet`, `meta`, `using`, etc. (fully standardized)
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* @param {Request} req
*
* @returns {Dictionary}
* The final dict of "blueprint options"; special settings that
* tell a blueprint action what to do when it runs. (They are
* roughly equivalent to Waterline query keys.)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
module.exports = function parseBlueprintOptions(req) {
// ββββββββββββββββββββββββββββ ββββββββββ
// ββββββββββββββββββββββββββββ βββββββββββ
// ββββββββββββββ βββ βββ βββββββββββ
// ββββββββββββββ βββ βββ ββββββββββ
// ββββββββββββββββ βββ ββββββββββββ
// ββββββββββββββββ βββ βββββββ βββ
// If you're copying code from one of the sections in the switch statement below,
// you'll probably also want to copy this setup code.
// Set some defaults.
var DEFAULT_LIMIT = 30;
var DEFAULT_POPULATE_LIMIT = 30;
// Get the name of the blueprint action being run.
var blueprint = req.options.blueprintAction;
// βββββββ¬ββββββββ ββ¬ββββββ¬βββββ¬
// ββββββ€ββ¬ββββββ€ ββββ β ββββ€ β
// β΄ β΄ β΄β΄ββββββββ β΄ β΄βββββ΄βββββ΄ββ
// Get the model identity from the action name (e.g. 'user/find').
var model = req.options.action.split('/')[0];
if (!model) { throw new Error(util.format('No "model" specified in route options.')); }
// Get the model class.
var Model = req._sails.models[model];
if ( !Model ) { throw new Error(util.format('Invalid route option, "model".\nI don\'t know about any models named: `%s`',model)); }
// ββ¬βββββββββββ¬ β¬β¬ ββ¬β ββββββββββ¬ β¬β¬ βββββ¬βββββββ
// ββββ€ ββ€ βββ€β ββ β ββββ βββββ ββ βββ€ β ββ€ βββ
// ββ΄βββββ β΄ β΄ββββ΄βββ΄ β΄ ββββ΄ ββββ΄βββ΄ β΄ β΄ ββββββ
// Get the default populates array
var defaultPopulates = _.reduce(Model.associations, function(memo, association) {
if (association.type === 'collection') {
memo[association.alias] = {
where: {},
limit: DEFAULT_POPULATE_LIMIT,
skip: 0,
select: [ '*' ],
omit: []
};
} else {
memo[association.alias] = {};
}
return memo;
}, {});
// Initialize the queryOptions dictionary we'll be returning.
var queryOptions = {
using: model,
populates: defaultPopulates
};
switch (blueprint) {
// βββββββββββββββ ββββββββββ βββ
// ββββββββββββββββ βββββββββββ ββββ
// ββββββ βββββββββ ββββββ βββ ββββ
// ββββββ ββββββββββββββββ βββ ββββ
// βββ ββββββ ββββββββββββββ ββββ
// βββ ββββββ ββββββββββββ βββ
//
// βββββββββββββββ ββββββββββ βββββββ ββββ βββββββββββ
// ββββββββββββββββ βββββββββββββββββββββββββ βββββββββββ
// ββββββ βββββββββ ββββββ ββββββ βββββββββ βββββββββ
// ββββββ ββββββββββββββββ ββββββ βββββββββββββββββββ
// βββ ββββββ ββββββββββββββββββββββββββ ββββββββββββββ
// βββ ββββββ ββββββββββββ βββββββ βββ βββββββββββββ
case 'find':
case 'findOne':
queryOptions.criteria = {};
// βββββββ¬ββββββββ ββββ¦βββ¦ββ¦βββββ¦βββ¦βββ
// ββββββ€ββ¬ββββββ€ β β β¦ββ β ββ£ β β¦βββ ββ£
// β΄ β΄ β΄β΄ββββββββ ββββ©βββ© β© ββββ©βββ©β© β©
queryOptions.criteria.where = (function getWhereCriteria(){
var where = {};
// For `findOne`, set "where" to just look at the primary key.
if (blueprint === 'findOne') {
where[Model.primaryKey] = req.param('id');
return where;
}
// Look for explicitly specified `where` parameter.
where = req.allParams().where;
// If `where` parameter is a string, try to interpret it as JSON.
// (If it cannot be parsed, throw a UsageError.)
if (_.isString(where)) {
try {
where = JSON.parse(where);
} catch (e) {
throw flaverr({ name: 'UsageError' }, new Error('Could not JSON.parse() the provided `where` clause. Here is the raw error: '+e.stack));
}
}//>-β’
// If `where` has not been specified, but other unbound parameter variables
// **ARE** specified, build the `where` option using them.
if (!where) {
// Prune params which aren't fit to be used as `where` criteria
// to build a proper where query
where = req.allParams();
// Omit built-in runtime config (like query modifiers)
where = _.omit(where, ['limit', 'skip', 'sort', 'populate', 'select', 'omit']);
// Omit any params that have `undefined` on the RHS.
where = _.omit(where, function(p) {
if (_.isUndefined(p)) { return true; }
});
}//>-
// Return final `where`.
return where;
})();
// βββββββ¬ββββββββ βββββββ¬ ββββββββ¬β
// ββββββ€ββ¬ββββββ€ βββββ€ β ββ€ β β
// β΄ β΄ β΄β΄ββββββββ βββββββ΄ββββββββ β΄
if (!_.isUndefined(req.param('select'))) {
queryOptions.criteria.select = req.param('select').split(',').map(function(attribute) {return attribute.trim();});
}
// βββββββ¬ββββββββ βββββ¬ββ¬ββ¬β
// ββββββ€ββ¬ββββββ€ β βββββ β
// β΄ β΄ β΄β΄ββββββββ ββββ΄ β΄β΄ β΄
else if (!_.isUndefined(req.param('omit'))) {
queryOptions.criteria.omit = req.param('omit').split(',').map(function(attribute) {return attribute.trim();});
}
// βββββββ¬ββββββββ β¬ β¬ββ¬ββ¬ββ¬β
// ββββββ€ββ¬ββββββ€ β βββββ β
// β΄ β΄ β΄β΄ββββββββ β΄βββ΄β΄ β΄β΄ β΄
if (!_.isUndefined(req.param('limit'))) {
queryOptions.criteria.limit = req.param('limit');
} else {
queryOptions.criteria.limit = DEFAULT_LIMIT;
}
// βββββββ¬ββββββββ ββββ¬βββ¬βββ
// ββββββ€ββ¬ββββββ€ βββββ΄βββββ
// β΄ β΄ β΄β΄ββββββββ ββββ΄ β΄β΄β΄
if (!_.isUndefined(req.param('skip'))) { queryOptions.criteria.skip = req.param('skip'); }
// βββββββ¬ββββββββ βββββββ¬ββββ¬β
// ββββββ€ββ¬ββββββ€ ββββ βββ¬β β
// β΄ β΄ β΄β΄ββββββββ βββββββ΄ββ β΄
if (!_.isUndefined(req.param('sort'))) {
queryOptions.criteria.sort = (function getSortCriteria() {
var sort = req.param('sort');
if (_.isUndefined(sort)) {return undefined;}
// If `sort` is a string, attempt to JSON.parse() it.
// (e.g. `{"name": 1}`)
if (_.isString(sort)) {
try {
sort = JSON.parse(sort);
// If it is not valid JSON (e.g. because it's just some other string),
// then just fall back to interpreting it as-is (e.g. "name ASC")
} catch (unusedErr) {
return sort;
}
}
return sort;
})();
}
// βββββββ¬ββββββββ ββββββββββ¬ β¬β¬ βββββ¬ββββ
// ββββββ€ββ¬ββββββ€ ββββ βββββ ββ βββ€ β ββ€
// β΄ β΄ β΄β΄ββββββββ β΄ ββββ΄ ββββ΄βββ΄ β΄ β΄ βββ
// If a `populate` param was sent, filter the attributes to populate
// against that value.
// e.g.:
// /model?populate=alias1,alias2,alias3
// /model?populate=[alias1,alias2,alias3]
if (req.param('populate')) {
queryOptions.populates = (function getPopulates() {
// Get the request param.
var attributes = req.param('populate');
// If it's `false`, populate nothing.
if (attributes === 'false') {
return {};
}
// Split the list on commas.
attributes = attributes.split(',');
// Trim whitespace off of the attributes.
attributes = _.reduce(attributes, function(memo, attribute) {
memo[attribute.trim()] = {};
return memo;
}, {});
return attributes;
})();
}
break;
// ββββββββββββββ ββββββββ ββββββ βββββββββββββββββ
// βββββββββββββββββββββββββββββββββββββββββββββββββ
// βββ ββββββββββββββ ββββββββ βββ ββββββ
// βββ ββββββββββββββ ββββββββ βββ ββββββ
// βββββββββββ ββββββββββββββ βββ βββ ββββββββ
// ββββββββββ ββββββββββββββ βββ βββ ββββββββ
case 'create':
// Set `fetch: true`
queryOptions.meta = { fetch: true };
// βββββββ¬ββββββββ β¬ β¬ββββ¬ β¬ β¬ββββββ
// ββββββ€ββ¬ββββββ€ βββββββ€β β βββ€ βββ
// β΄ β΄ β΄β΄ββββββββ ββ β΄ β΄β΄βββββββββββ
queryOptions.newRecord = (function getNewRecord(){
// Use all of the request params as values for the new record.
var values = req.allParams();
// Attempt to JSON parse any collection attributes into arrays. This is to allow
// setting collections using the shortcut routes.
_.each(Model.attributes, function(attrDef, attrName) {
if (attrDef.collection && (!req.body || !req.body[attrName]) && (req.query && _.isString(req.query[attrName]))) {
try {
values[attrName] = JSON.parse(req.query[attrName]);
// If it is not valid JSON (e.g. because it's just a normal string),
// then fall back to interpreting it as-is
} catch (unusedErr) {
values[attrName] = values[attrName];
}
}
});
return values;
})();
break;
// βββ ββββββββββ βββββββ ββββββ βββββββββββββββββ
// βββ ββββββββββββββββββββββββββββββββββββββββββββ
// βββ ββββββββββββββ βββββββββββ βββ ββββββ
// βββ ββββββββββ βββ βββββββββββ βββ ββββββ
// ββββββββββββ βββββββββββ βββ βββ ββββββββ
// βββββββ βββ βββββββ βββ βββ βββ ββββββββ
case 'update':
queryOptions.criteria = {
where: {}
};
queryOptions.criteria.where[Model.primaryKey] = req.param('id');
// Set `fetch: true`
queryOptions.meta = { fetch: true };
// βββββββ¬ββββββββ β¬ β¬ββββ¬ β¬ β¬ββββββ
// ββββββ€ββ¬ββββββ€ βββββββ€β β βββ€ βββ
// β΄ β΄ β΄β΄ββββββββ ββ β΄ β΄β΄βββββββββββ
queryOptions.valuesToSet = (function getValuesToSet(){
// Use all of the request params as values for the new record, _except_ `id`.
var values = _.omit(req.allParams(), 'id');
// No matter what, don't allow changing the PK via the update blueprint
// (you should just drop and re-add the record if that's what you really want)
if (typeof values[Model.primaryKey] !== 'undefined' && values[Model.primaryKey] !== queryOptions.criteria.where[Model.primaryKey]) {
req._sails.log.warn('Cannot change primary key via update blueprint; ignoring value sent for `' + Model.primaryKey + '`');
}
// Make sure the primary key is unchanged
values[Model.primaryKey] = queryOptions.criteria.where[Model.primaryKey];
return values;
})();
break;
// βββββββ ββββββββββββββββββββββββββββββββ βββββββ βββ βββ
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββββ
// βββ βββββββββ ββββββββ βββ βββββββββββ βββ βββββββ
// βββ βββββββββ ββββββββ βββ βββββββββββ βββ βββββ
// ββββββββββββββββββββββββ βββ βββ ββββββββββββ βββ
// βββββββ ββββββββββββββββ βββ βββ βββ βββββββ βββ
case 'destroy':
queryOptions.criteria = {};
queryOptions.criteria = {
where: {}
};
queryOptions.criteria.where[Model.primaryKey] = req.param('id');
// Set `fetch: true`
queryOptions.meta = { fetch: true };
break;
// ββββββ βββββββ βββββββ
// ββββββββββββββββββββββββ
// βββββββββββ ββββββ βββ
// βββββββββββ ββββββ βββ
// βββ βββββββββββββββββββ
// βββ ββββββββββ βββββββ
case 'add':
if (!req.options.alias) {
throw new Error('Missing required route option, `req.options.alias`.');
}
queryOptions.alias = req.options.alias;
queryOptions.targetRecordId = req.param('parentid');
queryOptions.associatedIds = [req.param('childid')];
break;
// βββββββ ββββββββββββ ββββ βββββββ βββ βββββββββββ
// βββββββββββββββββββββ βββββββββββββββββ βββββββββββ
// ββββββββββββββ ββββββββββββββ ββββββ βββββββββ
// ββββββββββββββ ββββββββββββββ βββββββ ββββββββββ
// βββ ββββββββββββββ βββ ββββββββββββ βββββββ ββββββββ
// βββ ββββββββββββββ βββ βββββββ βββββ ββββββββ
case 'remove':
if (!req.options.alias) {
throw new Error('Missing required route option, `req.options.alias`.');
}
queryOptions.alias = req.options.alias;
queryOptions.targetRecordId = req.param('parentid');
queryOptions.associatedIds = [req.param('childid')];
break;
// βββββββ βββββββββββββββ βββ ββββββ βββββββββββββββ
// βββββββββββββββββββββββββββ ββββββββββββββββββββββββ
// ββββββββββββββ βββββββββββ βββββββββββ ββββββ
// ββββββββββββββ βββββββ βββ βββββββββββ ββββββ
// βββ ββββββββββββββ βββββββββββ βββββββββββββββββββ
// βββ ββββββββββββββ βββββββββββ βββ βββββββββββββββ
case 'replace':
if (!req.options.alias) {
throw new Error('Missing required route option, `req.options.alias`.');
}
queryOptions.alias = req.options.alias;
queryOptions.criteria = {};
queryOptions.criteria = {
where: {}
};
queryOptions.targetRecordId = req.param('parentid');
queryOptions.associatedIds = _.isArray(req.body) ? req.body : req.query[req.options.alias];
if (_.isString(queryOptions.associatedIds)) {
try {
queryOptions.associatedIds = JSON.parse(queryOptions.associatedIds);
} catch (e) {
throw flaverr({ name: 'UsageError', raw: e }, new Error(
'The associated ids provided in this request (for the `' + req.options.alias + '` collection) are not valid. '+
'If specified as a string, the associated ids provided to the "replace" blueprint action must be parseable as '+
'a JSON array, e.g. `[1, 2]`.'
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE: Use smart example depending on the expected pk type (e.g. if string, show mongo ids instead)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
));
}//</catch>
}
break;
// βββββββ βββββββ βββββββ βββ ββββββ ββββββ βββββββββββββββββ
// ββββββββββββββββββββββββββββ ββββββ βββββββββββββββββββββββββ
// βββββββββββ ββββββββββββββ ββββββ ββββββββ βββ ββββββ
// βββββββ βββ ββββββββββ βββ ββββββ ββββββββ βββ ββββββ
// βββ ββββββββββββ ββββββββββββββββββββ βββ βββ ββββββββ
// βββ βββββββ βββ βββββββ βββββββββββ βββ βββ ββββββββ
case 'populate':
if (!req.options.alias) {
throw new Error('Missing required route option, `req.options.alias`.');
}
var association = _.find(Model.associations, {alias: req.options.alias});
if (!association) {
throw new Error('Consistency violation: `populate` blueprint could not find association `' + req.options.alias + '` in model `' + Model.globalId + '`.');
}
queryOptions.alias = req.options.alias;
queryOptions.criteria = {};
// βββββββ¬ββββββββ ββββ¦βββ¦ββ¦βββββ¦βββ¦βββ
// ββββββ€ββ¬ββββββ€ β β β¦ββ β ββ£ β β¦βββ ββ£
// β΄ β΄ β΄β΄ββββββββ ββββ©βββ© β© ββββ©βββ©β© β©
queryOptions.criteria = {};
queryOptions.criteria = {
where: {}
};
queryOptions.criteria.where[Model.primaryKey] = req.param('parentid');
queryOptions.populates = {};
queryOptions.populates[req.options.alias] = {};
// If this is a to-many association, add a `where` clause.
if (association.collection) {
queryOptions.populates[req.options.alias].where = (function getPopulateCriteria(){
var where = req.allParams().where;
// If `where` parameter is a string, try to interpret it as JSON.
// (If it cannot be parsed, throw a UsageError.)
if (_.isString(where)) {
try {
where = JSON.parse(where);
} catch (e) {
throw flaverr({ name: 'UsageError' }, new Error('Could not JSON.parse() the provided `where` clause. Here is the raw error: '+e.stack));
}
}//>-β’
// If `where` has not been specified, but other unbound parameter variables
// **ARE** specified, build the `where` option using them.
if (!where) {
// Prune params which aren't fit to be used as `where` criteria
// to build a proper where query
where = req.allParams();
// Omit built-in runtime config (like top-level criteria clauses)
where = _.omit(where, ['limit', 'skip', 'sort', 'populate', 'select', 'omit', 'parentid']);
// - - - - - - - - - - - - - - - - - - - - -
// ^^TODO: what about `where` itself?
// - - - - - - - - - - - - - - - - - - - - -
// Omit any params that have `undefined` on the RHS.
where = _.omit(where, function(p) {
if (_.isUndefined(p)) { return true; }
});
}//>-
// Return final `where`.
return where;
})();
}
// βββββββ¬ββββββββ βββββββ¬ ββββββββ¬β
// ββββββ€ββ¬ββββββ€ βββββ€ β ββ€ β β
// β΄ β΄ β΄β΄ββββββββ βββββββ΄ββββββββ β΄
if (!_.isUndefined(req.param('select'))) {
queryOptions.populates[req.options.alias].select = req.param('select').split(',').map(function(attribute) {return attribute.trim();});
}
// βββββββ¬ββββββββ βββββ¬ββ¬ββ¬β
// ββββββ€ββ¬ββββββ€ β βββββ β
// β΄ β΄ β΄β΄ββββββββ ββββ΄ β΄β΄ β΄
else if (!_.isUndefined(req.param('omit'))) {
queryOptions.populates[req.options.alias].omit = req.param('omit').split(',').map(function(attribute) {return attribute.trim();});
}
//
// βββββββ¬ββββββββ β¬ β¬ββ¬ββ¬ββ¬β
// ββββββ€ββ¬ββββββ€ β βββββ β
// β΄ β΄ β΄β΄ββββββββ β΄βββ΄β΄ β΄β΄ β΄
if (!_.isUndefined(req.param('limit'))) {
queryOptions.populates[req.options.alias].limit = req.param('limit');
}
// If this is a to-many association, use the default limit if not was provided.
else if (association.collection) {
queryOptions.populates[req.options.alias].limit = DEFAULT_LIMIT;
}
// βββββββ¬ββββββββ ββββ¬βββ¬βββ
// ββββββ€ββ¬ββββββ€ βββββ΄βββββ
// β΄ β΄ β΄β΄ββββββββ ββββ΄ β΄β΄β΄
if (!_.isUndefined(req.param('skip'))) { queryOptions.populates[req.options.alias].skip = req.param('skip'); }
// βββββββ¬ββββββββ βββββββ¬ββββ¬β
// ββββββ€ββ¬ββββββ€ ββββ βββ¬β β
// β΄ β΄ β΄β΄ββββββββ βββββββ΄ββ β΄
if (!_.isUndefined(req.param('sort'))) {
queryOptions.populates[req.options.alias].sort = (function getSortCriteria() {
var sort = req.param('sort');
if (_.isUndefined(sort)) {return undefined;}
// If `sort` is a string, attempt to JSON.parse() it.
// (e.g. `{"name": 1}`)
if (_.isString(sort)) {
try {
sort = JSON.parse(sort);
// If it is not valid JSON (e.g. because it's just a normal string),
// then fall back to interpreting it as-is (e.g. "fullName ASC")
} catch (unusedErr) {
return sort;
}
}
return sort;
})();//Λ
}
break;
}
return queryOptions;
};