-
Notifications
You must be signed in to change notification settings - Fork 0
/
actionUtil.js
404 lines (325 loc) · 12.3 KB
/
actionUtil.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
/**
* Module dependencies
*/
var util = require('util');
var isString = require('lodash.isstring');
var isArray = require('lodash.isarray');
var isObject = require('lodash.isobject');
var isUndefined = require('lodash.isundefined');
var _ = require('lodash'); // TODO: replace lodash with individual per-method packages
var mergeDefaults = require('merge-defaults');
// Parameter used for jsonp callback is constant, as far as
// blueprints are concerned (for now.)
var JSONP_CALLBACK_PARAM = 'callback';
/**
* Utility methods used in built-in blueprint actions.
*
* @type {Object}
*/
var actionUtil = {
/**
* Given a Waterline query and an express request, populate
* the appropriate/specified association attributes and
* return it so it can be chained further ( i.e. so you can
* .exec() it )
*
* @param {Query} query [waterline query object]
* @param {Request} req
* @return {Query}
*/
populateRequest: function(query, req) {
var DEFAULT_POPULATE_LIMIT = req._sails.config.blueprints.defaultLimit || 30;
var _options = req.options;
var aliasFilter = req.param('populate');
var shouldPopulate = _options.populate;
// Convert the string representation of the filter list to an Array. We
// need this to provide flexibility in the request param. This way both
// list string representations are supported:
// /model?populate=alias1,alias2,alias3
// /model?populate=[alias1,alias2,alias3]
if (typeof aliasFilter === 'string') {
aliasFilter = aliasFilter.replace(/\[|\]/g, '');
aliasFilter = (aliasFilter) ? aliasFilter.split(',') : [];
}
var associations = [];
_.each(_options.associations, function(association) {
// If an alias filter was provided, override the blueprint config.
if (aliasFilter) {
shouldPopulate = _.contains(aliasFilter, association.alias);
}
// Only populate associations if a population filter has been supplied
// with the request or if `populate` is set within the blueprint config.
// Population filters will override any value stored in the config.
//
// Additionally, allow an object to be specified, where the key is the
// name of the association attribute, and value is true/false
// (true to populate, false to not)
if (shouldPopulate) {
var populationLimit =
_options['populate_' + association.alias + '_limit'] ||
_options.populate_limit ||
_options.limit ||
DEFAULT_POPULATE_LIMIT;
associations.push({
alias: association.alias,
limit: populationLimit
});
}
});
return actionUtil.populateQuery(query, associations, req._sails);
},
/**
* Given a Waterline query and Waterline model, populate the
* appropriate/specified association attributes and return it
* so it can be chained further ( i.e. so you can .exec() it )
*
* @param {Query} query [waterline query object]
* @param {Model} model [waterline model object]
* @return {Query}
*/
populateModel: function(query, model) {
return actionUtil.populateQuery(query, model.associations);
},
/**
* Given a Waterline query, populate the appropriate/specified
* association attributes and return it so it can be chained
* further ( i.e. so you can .exec() it )
*
* @param {Query} query [waterline query object]
* @param {Array} associations [array of objects with an alias
* and (optional) limit key]
* @return {Query}
*/
populateQuery: function(query, associations, sails) {
var DEFAULT_POPULATE_LIMIT = (sails && sails.config.blueprints.defaultLimit) || 30;
return _.reduce(associations, function(query, association) {
return query.populate(association.alias, {
limit: association.limit || DEFAULT_POPULATE_LIMIT
});
}, query);
},
/**
* Subscribe deep (associations)
*
* @param {[type]} associations [description]
* @param {[type]} record [description]
* @return {[type]} [description]
*/
subscribeDeep: function ( req, record ) {
_.each(req.options.associations, function (assoc) {
// Look up identity of associated model
var ident = assoc[assoc.type];
var AssociatedModel = req._sails.models[ident];
if (req.options.autoWatch) {
AssociatedModel.watch(req);
}
// Subscribe to each associated model instance in a collection
if (assoc.type === 'collection') {
_.each(record[assoc.alias], function (associatedInstance) {
AssociatedModel.subscribe(req, associatedInstance);
});
}
// If there is an associated to-one model instance, subscribe to it
else if (assoc.type === 'model' && record[assoc.alias]) {
AssociatedModel.subscribe(req, record[assoc.alias]);
}
});
},
/**
* Parse primary key value for use in a Waterline criteria
* (e.g. for `find`, `update`, or `destroy`)
*
* @param {Request} req
* @return {Integer|String}
*/
parsePk: function ( req ) {
var pk = req.options.id || (req.options.where && req.options.where.id) || req.param('id');
// TODO: make this smarter...
// (e.g. look for actual primary key of model and look for it
// in the absence of `id`.)
// See coercePK for reference (although be aware it is not currently in use)
// exclude criteria on id field
pk = _.isPlainObject(pk) ? undefined : pk;
return pk;
},
/**
* Parse primary key value from parameters.
* Throw an error if it cannot be retrieved.
*
* @param {Request} req
* @return {Integer|String}
*/
requirePk: function (req) {
var pk = module.exports.parsePk(req);
// Validate the required `id` parameter
if ( !pk ) {
var err = new Error(
'No `id` parameter provided.'+
'(Note: even if the model\'s primary key is not named `id`- '+
'`id` should be used as the name of the parameter- it will be '+
'mapped to the proper primary key name)'
);
err.status = 400;
throw err;
}
return pk;
},
/**
* Parse `criteria` for a Waterline `find` or `update` from all
* request parameters.
*
* @param {Request} req
* @return {Object} the WHERE criteria object
*/
parseCriteria: function ( req ) {
// Allow customizable blacklist for params NOT to include as criteria.
req.options.criteria = req.options.criteria || {};
req.options.criteria.blacklist = req.options.criteria.blacklist || ['limit', 'skip', 'sort', 'populate'];
// Validate blacklist to provide a more helpful error msg.
var blacklist = req.options.criteria && req.options.criteria.blacklist;
if (blacklist && !isArray(blacklist)) {
throw new Error('Invalid `req.options.criteria.blacklist`. Should be an array of strings (parameter names.)');
}
// Look for explicitly specified `where` parameter.
var where = req.params.all().where;
// If `where` parameter is a string, try to interpret it as JSON
if (isString(where)) {
where = tryToParseJSON(where);
}
// 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.params.all();
// Omit built-in runtime config (like query modifiers)
where = _.omit(where, blacklist || ['limit', 'skip', 'sort']);
// Omit any params w/ undefined values
where = _.omit(where, function(p) {
if (isUndefined(p)) {return true;}
});
// Omit jsonp callback param (but only if jsonp is enabled)
var jsonpOpts = req.options.jsonp && !req.isSocket;
jsonpOpts = isObject(jsonpOpts) ? jsonpOpts : { callback: JSONP_CALLBACK_PARAM };
if (jsonpOpts) {
where = _.omit(where, [jsonpOpts.callback]);
}
}
// Merge w/ req.options.where and return
where = _.merge({}, req.options.where || {}, where) || undefined;
return where;
},
/**
* Parse `values` for a Waterline `create` or `update` from all
* request parameters.
*
* @param {Request} req
* @return {Object}
*/
parseValues: function (req) {
// Allow customizable blacklist for params NOT to include as values.
req.options.values = req.options.values || {};
req.options.values.blacklist = req.options.values.blacklist;
// Validate blacklist to provide a more helpful error msg.
var blacklist = req.options.values.blacklist;
if (blacklist && !isArray(blacklist)) {
throw new Error('Invalid `req.options.values.blacklist`. Should be an array of strings (parameter names.)');
}
// Start an array to hold values
var values;
// Make an array out of the request body data if it wasn't one already;
// this allows us to process multiple entities (e.g. for use with a "create" blueprint) the same way
// that we process singular entities.
var bodyData = isArray(req.body) ? req.body : [req.allParams()];
// Process each item in the bodyData array, merging with req.options, omitting blacklisted properties, etc.
var valuesArray = _.map(bodyData, function(element){
var values;
// Merge properties of the element into req.options.value, omitting the blacklist
values = mergeDefaults(element, _.omit(req.options.values, 'blacklist'));
// Omit properties that are in the blacklist (like query modifiers)
values = _.omit(values, blacklist || []);
// Omit any properties w/ undefined values
values = _.omit(values, function(p) {
if (isUndefined(p)) {
return true;
}
});
return values;
});
// If req.body is an array, simply return our array of processed values
if (isArray(req.body)) {return valuesArray;}
// Otherwaise grab the first (and only) value from valuesArray
values = valuesArray[0];
// Omit jsonp callback param (but only if jsonp is enabled)
var jsonpOpts = req.options.jsonp && !req.isSocket;
jsonpOpts = isObject(jsonpOpts) ? jsonpOpts : { callback: JSONP_CALLBACK_PARAM };
if (jsonpOpts) {
values = _.omit(values, [jsonpOpts.callback]);
}
return values;
},
/**
* Determine the model class to use w/ this blueprint action.
* @param {Request} req
* @return {WLCollection}
*/
parseModel: function (req) {
// Ensure a model can be deduced from the request options.
var model = req.options.model || req.options.controller;
if (!model) throw new Error(util.format('No "model" specified in route options.'));
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));
return Model;
},
/**
* @param {Request} req
*/
parseSort: function (req) {
var sort = req.param('sort') || req.options.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, then fall back to interpreting it as-is.
// (e.g. "name ASC")
catch(e) {}
}
return sort;
},
/**
* @param {Request} req
*/
parseLimit: function (req) {
var DEFAULT_LIMIT = req._sails.config.blueprints.defaultLimit || 30;
var limit = req.param('limit') || (typeof req.options.limit !== 'undefined' ? req.options.limit : DEFAULT_LIMIT);
if (limit) { limit = +limit; }
return limit;
},
/**
* @param {Request} req
*/
parseSkip: function (req) {
var DEFAULT_SKIP = 0;
var skip = req.param('skip') || (typeof req.options.skip !== 'undefined' ? req.options.skip : DEFAULT_SKIP);
if (skip) { skip = +skip; }
return skip;
}
};
// TODO:
//
// Replace the following helper with the version in sails.util:
// Attempt to parse JSON
// If the parse fails, return the error object
// If JSON is falsey, return null
// (this is so that it will be ignored if not specified)
function tryToParseJSON (json) {
if (!isString(json)) return null;
try {
return JSON.parse(json);
}
catch (e) { return e; }
}
module.exports = actionUtil;