forms-angular 0.12.0-beta.26 → 0.12.0-beta.261

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.
@@ -1,21 +1,38 @@
1
- 'use strict';
1
+ "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- // This part of forms-angular borrows _very_ heavily from https://github.com/Alexandre-Strzelewicz/angular-bridge
3
+ exports.FormsAngular = void 0;
4
+ const mongoose_1 = require("mongoose");
5
+ // This part of forms-angular borrows from https://github.com/Alexandre-Strzelewicz/angular-bridge
4
6
  // (now https://github.com/Unitech/angular-bridge
5
- var _ = require('lodash');
6
- var util = require('util');
7
- var extend = require('node.extend');
8
- var async = require('async');
9
- var debug = false;
7
+ const _ = require('lodash');
8
+ const util = require('util');
9
+ const extend = require('node.extend');
10
+ const async = require('async');
11
+ let debug = false;
10
12
  function logTheAPICalls(req, res, next) {
11
13
  void (res);
12
14
  console.log('API : ' + req.method + ' ' + req.url + ' [ ' + JSON.stringify(req.body) + ' ]');
13
15
  next();
14
16
  }
17
+ var entityMap = {
18
+ '&': '&',
19
+ '<': '&lt;',
20
+ '>': '&gt;',
21
+ '"': '&quot;',
22
+ "'": '&#39;',
23
+ '/': '&#x2F;',
24
+ '`': '&#x60;',
25
+ '=': '&#x3D;'
26
+ };
27
+ function escapeHtml(string) {
28
+ return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap(s) {
29
+ return entityMap[s];
30
+ });
31
+ }
15
32
  function processArgs(options, array) {
16
33
  if (options.authentication) {
17
- var authArray = _.isArray(options.authentication) ? options.authentication : [options.authentication];
18
- for (var i = authArray.length - 1; i >= 0; i--) {
34
+ let authArray = _.isArray(options.authentication) ? options.authentication : [options.authentication];
35
+ for (let i = authArray.length - 1; i >= 0; i--) {
19
36
  array.splice(1, 0, authArray[i]);
20
37
  }
21
38
  }
@@ -25,251 +42,414 @@ function processArgs(options, array) {
25
42
  array[0] = options.urlPrefix + array[0];
26
43
  return array;
27
44
  }
28
- var DataForm = function (mongoose, app, options) {
29
- this.app = app;
30
- app.locals.formsAngular = app.locals.formsAngular || [];
31
- app.locals.formsAngular.push(this);
32
- this.mongoose = mongoose;
33
- mongoose.set('debug', debug);
34
- mongoose.Promise = global.Promise;
35
- this.options = _.extend({
36
- urlPrefix: '/api/'
37
- }, options || {});
38
- this.resources = [];
39
- this.searchFunc = async.forEach;
40
- this.registerRoutes();
41
- this.app.get.apply(this.app, processArgs(this.options, ['search', this.searchAll()]));
42
- for (var pluginName in this.options.plugins) {
43
- var pluginObj = this.options.plugins[pluginName];
44
- this[pluginName] = pluginObj.plugin(this, processArgs, pluginObj.options);
45
+ class FormsAngular {
46
+ constructor(mongoose, app, options) {
47
+ this.mongoose = mongoose;
48
+ this.app = app;
49
+ app.locals.formsAngular = app.locals.formsAngular || [];
50
+ app.locals.formsAngular.push(this);
51
+ mongoose.set('debug', debug);
52
+ mongoose.Promise = global.Promise;
53
+ this.options = _.extend({
54
+ urlPrefix: '/api/'
55
+ }, options || {});
56
+ this.resources = [];
57
+ this.searchFunc = async.forEach;
58
+ // Do the plugin routes first
59
+ for (let pluginName in this.options.plugins) {
60
+ if (this.options.plugins.hasOwnProperty(pluginName)) {
61
+ let pluginObj = this.options.plugins[pluginName];
62
+ this.options.plugins[pluginName] = Object.assign(this.options.plugins[pluginName], pluginObj.plugin(this, processArgs, pluginObj.options));
63
+ }
64
+ }
65
+ const search = 'search/', schema = 'schema/', report = 'report/', resourceName = ':resourceName', id = '/:id', formName = '/:formName', newClarifier = '/new';
66
+ this.app.get.apply(this.app, processArgs(this.options, ['models', this.models()]));
67
+ this.app.get.apply(this.app, processArgs(this.options, [search + resourceName, this.search()]));
68
+ this.app.get.apply(this.app, processArgs(this.options, [schema + resourceName, this.schema()]));
69
+ this.app.get.apply(this.app, processArgs(this.options, [schema + resourceName + formName, this.schema()]));
70
+ this.app.get.apply(this.app, processArgs(this.options, [report + resourceName, this.report()]));
71
+ this.app.get.apply(this.app, processArgs(this.options, [report + resourceName + '/:reportName', this.report()]));
72
+ this.app.get.apply(this.app, processArgs(this.options, [resourceName, this.collectionGet()]));
73
+ // return the List attributes for all records - used by record-handler's setUpLookupOptions() method, for cases
74
+ // where there's a lookup that doesn't use the fngajax option
75
+ this.app.get.apply(this.app, processArgs(this.options, [resourceName + '/listAll', this.entityListAll()]));
76
+ // return the List attributes for a record - used by fng-ui-select
77
+ this.app.get.apply(this.app, processArgs(this.options, [resourceName + id + '/list', this.entityList()]));
78
+ // 2x get, with and without formName
79
+ this.app.get.apply(this.app, processArgs(this.options, [resourceName + id, this.entityGet()]));
80
+ this.app.get.apply(this.app, processArgs(this.options, [resourceName + formName + id, this.entityGet()])); // We don't use the form name, but it can optionally be included so it can be referenced by the permissions check
81
+ // 3x post (for creating a new record), with and without formName, and in the case of without, with or without /new (which isn't needed if there's no formName)
82
+ this.app.post.apply(this.app, processArgs(this.options, [resourceName, this.collectionPost()]));
83
+ this.app.post.apply(this.app, processArgs(this.options, [resourceName + newClarifier, this.collectionPost()]));
84
+ this.app.post.apply(this.app, processArgs(this.options, [resourceName + formName + newClarifier, this.collectionPost()]));
85
+ // 2x post and 2x put (for saving modifications to existing record), with and without formName
86
+ // (You can POST or PUT to update data)
87
+ this.app.post.apply(this.app, processArgs(this.options, [resourceName + id, this.entityPut()]));
88
+ this.app.post.apply(this.app, processArgs(this.options, [resourceName + formName + id, this.entityPut()]));
89
+ this.app.put.apply(this.app, processArgs(this.options, [resourceName + id, this.entityPut()]));
90
+ this.app.put.apply(this.app, processArgs(this.options, [resourceName + formName + id, this.entityPut()]));
91
+ // 2x delete, with and without formName
92
+ this.app.delete.apply(this.app, processArgs(this.options, [resourceName + id, this.entityDelete()]));
93
+ this.app.delete.apply(this.app, processArgs(this.options, [resourceName + formName + id, this.entityDelete()]));
94
+ this.app.get.apply(this.app, processArgs(this.options, ['search', this.searchAll()]));
45
95
  }
46
- };
47
- module.exports = exports = DataForm;
48
- DataForm.prototype.extractTimestampFromMongoID = function (record) {
49
- var timestamp = record.toString().substring(0, 8);
50
- return new Date(parseInt(timestamp, 16) * 1000);
51
- };
52
- DataForm.prototype.getListFields = function (resource, doc, cb) {
53
- function getFirstMatchingField(keyList, type) {
54
- for (var i = 0; i < keyList.length; i++) {
55
- var fieldDetails = resource.model.schema['tree'][keyList[i]];
96
+ getFirstMatchingField(resource, doc, keyList, type) {
97
+ for (let i = 0; i < keyList.length; i++) {
98
+ let fieldDetails = resource.model.schema['tree'][keyList[i]];
56
99
  if (fieldDetails.type && (!type || fieldDetails.type.name === type) && keyList[i] !== '_id') {
57
100
  resource.options.listFields = [{ field: keyList[i] }];
58
- return doc[keyList[i]];
101
+ return doc ? doc[keyList[i]] : keyList[i];
59
102
  }
60
103
  }
61
104
  }
62
- var that = this;
63
- var display = '';
64
- var listFields = resource.options.listFields;
65
- if (listFields) {
66
- async.map(listFields, function (aField, cbm) {
67
- if (typeof doc[aField.field] !== 'undefined') {
68
- if (aField.params) {
69
- if (aField.params.ref) {
70
- var fieldOptions = resource.model.schema['paths'][aField.field].options;
71
- if (typeof fieldOptions.ref === 'string') {
72
- fieldOptions.ref = { type: 'lookup', collection: fieldOptions.ref };
73
- console.log('Deprecation warning: invalid ref should be ' + JSON.stringify(fieldOptions.ref));
74
- }
75
- if (fieldOptions.ref.type === 'lookup') {
76
- var lookupResource_1 = that.getResource(fieldOptions.ref.collection);
77
- if (lookupResource_1) {
78
- var hiddenFields = that.generateHiddenFields(lookupResource_1, false);
79
- hiddenFields.__v = 0;
80
- lookupResource_1.model.findOne({ _id: doc[aField.field] }).select(hiddenFields).exec(function (err, doc2) {
81
- if (err) {
105
+ getListFields(resource, doc, cb) {
106
+ const that = this;
107
+ let display = '';
108
+ let listFields = resource.options.listFields;
109
+ if (listFields) {
110
+ async.map(listFields, function (aField, cbm) {
111
+ if (typeof doc[aField.field] !== 'undefined') {
112
+ if (aField.params) {
113
+ if (aField.params.ref) {
114
+ let fieldOptions = resource.model.schema['paths'][aField.field].options;
115
+ if (typeof fieldOptions.ref === 'string') {
116
+ let lookupResource = that.getResource(fieldOptions.ref);
117
+ if (lookupResource) {
118
+ let hiddenFields = that.generateHiddenFields(lookupResource, false);
119
+ hiddenFields.__v = false;
120
+ lookupResource.model
121
+ .findOne({ _id: doc[aField.field] })
122
+ .select(hiddenFields)
123
+ .exec()
124
+ .then((doc2) => {
125
+ that.getListFields(lookupResource, doc2, cbm);
126
+ })
127
+ .catch((err) => {
82
128
  cbm(err);
83
- }
84
- else {
85
- that.getListFields(lookupResource_1, doc2, cbm);
86
- }
87
- });
129
+ });
130
+ }
131
+ }
132
+ else {
133
+ throw new Error('No support for ref type ' + aField.params.ref.type);
88
134
  }
89
135
  }
90
- else {
91
- throw new Error('No support for ref type ' + aField.params.ref.type);
136
+ else if (aField.params.params === 'timestamp') {
137
+ let date = that.extractTimestampFromMongoID(doc[aField.field]);
138
+ cbm(null, date.toLocaleDateString() + ' ' + date.toLocaleTimeString());
92
139
  }
93
140
  }
94
- else if (aField.params.params === 'timestamp') {
95
- var date = this.extractTimestampFromMongoID(doc[aField.field]);
96
- cbm(null, date.toLocaleDateString() + ' ' + date.toLocaleTimeString());
141
+ else {
142
+ cbm(null, doc[aField.field]);
97
143
  }
98
144
  }
99
145
  else {
100
- cbm(null, doc[aField.field]);
146
+ cbm(null, '');
101
147
  }
102
- }
103
- else {
104
- cbm(null, '');
105
- }
106
- }, function (err, results) {
107
- if (err) {
108
- cb(err);
109
- }
110
- else {
111
- if (results) {
112
- cb(err, results.join(' ').trim());
148
+ }, function (err, results) {
149
+ if (err) {
150
+ cb(err);
113
151
  }
114
152
  else {
115
- console.log('No results ' + listFields);
153
+ if (results) {
154
+ cb(err, results.join(' ').trim());
155
+ }
156
+ else {
157
+ console.log('No results ' + listFields);
158
+ }
116
159
  }
117
- }
118
- });
119
- }
120
- else {
121
- var keyList = Object.keys(resource.model.schema['tree']);
122
- // No list field specified - use the first String field,
123
- display = getFirstMatchingField(keyList, 'String') ||
124
- // and if there aren't any then just take the first field
125
- getFirstMatchingField(keyList);
126
- cb(null, display.trim());
127
- }
128
- };
129
- /**
130
- * Registers all REST routes with the provided `app` object.
131
- */
132
- DataForm.prototype.registerRoutes = function () {
133
- var search = 'search/', schema = 'schema/', report = 'report/', resourceName = ':resourceName', id = '/:id';
134
- this.app.get.apply(this.app, processArgs(this.options, ['models', this.models()]));
135
- this.app.get.apply(this.app, processArgs(this.options, [search + resourceName, this.search()]));
136
- this.app.get.apply(this.app, processArgs(this.options, [schema + resourceName, this.schema()]));
137
- this.app.get.apply(this.app, processArgs(this.options, [schema + resourceName + '/:formName', this.schema()]));
138
- this.app.get.apply(this.app, processArgs(this.options, [report + resourceName, this.report()]));
139
- this.app.get.apply(this.app, processArgs(this.options, [report + resourceName + '/:reportName', this.report()]));
140
- this.app.get.apply(this.app, processArgs(this.options, [resourceName, this.collectionGet()]));
141
- this.app.post.apply(this.app, processArgs(this.options, [resourceName, this.collectionPost()]));
142
- this.app.get.apply(this.app, processArgs(this.options, [resourceName + id, this.entityGet()]));
143
- this.app.post.apply(this.app, processArgs(this.options, [resourceName + id, this.entityPut()])); // You can POST or PUT to update data
144
- this.app.put.apply(this.app, processArgs(this.options, [resourceName + id, this.entityPut()]));
145
- this.app.delete.apply(this.app, processArgs(this.options, [resourceName + id, this.entityDelete()]));
146
- // return the List attributes for a record - used by select2
147
- this.app.get.apply(this.app, processArgs(this.options, [resourceName + id + '/list', this.entityList()]));
148
- };
149
- DataForm.prototype.newResource = function (model, options) {
150
- options = options || {};
151
- options.suppressDeprecatedMessage = true;
152
- var passModel = model;
153
- if (typeof model !== 'function') {
154
- passModel = model.model;
155
- }
156
- this.addResource(passModel.modelName, passModel, options);
157
- };
158
- // Add a resource, specifying the model and any options.
159
- // Models may include their own options, which means they can be passed through from the model file
160
- DataForm.prototype.addResource = function (resourceName, model, options) {
161
- var resource = {
162
- resourceName: resourceName,
163
- options: options || {}
164
- };
165
- if (!resource.options.suppressDeprecatedMessage) {
166
- console.log('addResource is deprecated - see https://github.com/forms-angular/forms-angular/issues/39');
167
- }
168
- if (typeof model === 'function') {
169
- resource.model = model;
160
+ });
161
+ }
162
+ else {
163
+ const keyList = Object.keys(resource.model.schema['tree']);
164
+ // No list field specified - use the first String field,
165
+ display = this.getFirstMatchingField(resource, doc, keyList, 'String') ||
166
+ // and if there aren't any then just take the first field
167
+ this.getFirstMatchingField(resource, doc, keyList);
168
+ cb(null, display.trim());
169
+ }
170
170
  }
171
- else {
172
- resource.model = model.model;
173
- for (var prop in model) {
174
- if (model.hasOwnProperty(prop) && prop !== 'model') {
175
- resource.options[prop] = model[prop];
171
+ ;
172
+ // generate a Mongo projection that can be used to restrict a query to return only those fields from the given
173
+ // resource that are identified as "list" fields (i.e., ones that should appear whenever records of that type are
174
+ // displayed in a list)
175
+ generateListFieldProjection(resource) {
176
+ const projection = {};
177
+ const listFields = resource.options?.listFields;
178
+ // resource.options.listFields will identify all of the fields from resource that have a value for .list.
179
+ // generally, that value will be "true", identifying the corresponding field as one which should be
180
+ // included whenever records of that type appear in a list.
181
+ // occasionally, it will instead be "{ ref: true }"", which means something entirely different -
182
+ // this means that the field requires a lookup translation before it can be displayed on a form.
183
+ // for our purposes, we're interested in only the first of these two cases, so we'll ignore anything where
184
+ // field.params.ref has a truthy value
185
+ if (listFields) {
186
+ for (const field of listFields) {
187
+ if (!field.params?.ref) {
188
+ projection[field.field] = 1;
189
+ }
176
190
  }
177
191
  }
192
+ else {
193
+ const keyList = Object.keys(resource.model.schema['tree']);
194
+ const firstField = (
195
+ // No list field specified - use the first String field,
196
+ this.getFirstMatchingField(resource, undefined, keyList, 'String') ||
197
+ // and if there aren't any then just take the first field
198
+ this.getFirstMatchingField(resource, undefined, keyList));
199
+ projection[firstField] = 1;
200
+ }
201
+ return projection;
178
202
  }
179
- extend(resource.options, this.preprocess(resource, resource.model.schema['paths'], null));
180
- if (resource.options.searchImportance) {
181
- this.searchFunc = async.forEachSeries;
203
+ ;
204
+ newResource(model, options) {
205
+ options = options || {};
206
+ options.suppressDeprecatedMessage = true;
207
+ let passModel = model;
208
+ if (typeof model !== 'function') {
209
+ passModel = model.model;
210
+ }
211
+ this.addResource(passModel.modelName, passModel, options);
182
212
  }
183
- if (this.searchFunc === async.forEachSeries) {
184
- this.resources.splice(_.sortedIndexBy(this.resources, resource, function (obj) {
185
- return obj.options.searchImportance || 99;
186
- }), 0, resource);
213
+ ;
214
+ // Add a resource, specifying the model and any options.
215
+ // Models may include their own options, which means they can be passed through from the model file
216
+ addResource(resourceName, model, options) {
217
+ let resource = {
218
+ resourceName: resourceName,
219
+ resourceNameLower: resourceName.toLowerCase(),
220
+ options: options || {}
221
+ };
222
+ if (!resource.options.suppressDeprecatedMessage) {
223
+ console.log('addResource is deprecated - see https://github.com/forms-angular/forms-angular/issues/39');
224
+ }
225
+ // Check all the synonyms are lower case
226
+ resource.options.synonyms?.forEach(s => { s.name = s.name.toLowerCase(); });
227
+ if (typeof model === 'function') {
228
+ resource.model = model;
229
+ }
230
+ else {
231
+ resource.model = model.model;
232
+ for (const prop in model) {
233
+ if (model.hasOwnProperty(prop) && prop !== 'model') {
234
+ resource.options[prop] = model[prop];
235
+ }
236
+ }
237
+ }
238
+ extend(resource.options, this.preprocess(resource, resource.model.schema['paths']));
239
+ if (resource.options.searchImportance) {
240
+ this.searchFunc = async.forEachSeries;
241
+ }
242
+ if (this.searchFunc === async.forEachSeries) {
243
+ this.resources.splice(_.sortedIndexBy(this.resources, resource, function (obj) {
244
+ return obj.options.searchImportance || 99;
245
+ }), 0, resource);
246
+ }
247
+ else {
248
+ this.resources.push(resource);
249
+ }
187
250
  }
188
- else {
189
- this.resources.push(resource);
251
+ ;
252
+ getResource(name) {
253
+ return _.find(this.resources, function (resource) {
254
+ return resource.resourceName === name || resource.options.resourceName === name;
255
+ });
190
256
  }
191
- };
192
- DataForm.prototype.getResource = function (name) {
193
- return _.find(this.resources, function (resource) {
194
- return resource.resourceName === name;
195
- });
196
- };
197
- DataForm.prototype.getResourceFromCollection = function (name) {
198
- return _.find(this.resources, function (resource) {
199
- return resource.model.collection.collectionName === name;
200
- });
201
- };
202
- DataForm.prototype.internalSearch = function (req, resourcesToSearch, includeResourceInResults, limit, callback) {
203
- if (typeof req.query === 'undefined') {
204
- req.query = {};
257
+ ;
258
+ getResourceFromCollection(name) {
259
+ return _.find(this.resources, function (resource) {
260
+ return resource.model.collection.collectionName === name;
261
+ });
205
262
  }
206
- var searches = [], resourceCount = resourcesToSearch.length, searchFor = req.query.q || '', filter = req.query.f;
207
- function translate(string, array, context) {
208
- if (array) {
209
- var translation = _.find(array, function (fromTo) {
210
- return fromTo.from === string && (!fromTo.context || fromTo.context === context);
263
+ ;
264
+ // Using the given (already-populated) AmbiguousRecordStore, generate text suitable for
265
+ // disambiguation of each ambiguous record, and pass that to the given disambiguateItemCallback
266
+ // so our caller can decorate the ambiguous record in whatever way it deems appropriate.
267
+ //
268
+ // The ambiguousRecordStore provided to this function (generated either by a call to
269
+ // buildSingleResourceAmbiguousRecordStore() or buildMultiResourceAmbiguousRecordStore()) will
270
+ // already be grouping records by the resource that should be used to disambiguate them, with
271
+ // the name of that resource being the primary index property of the store.
272
+ //
273
+ // The disambiguation text will be the concatenation (space-seperated) of the list fields for
274
+ // the doc from that resource whose _id matches the value of record[disambiguationField].
275
+ //
276
+ // allRecords should include all of the ambiguous records (also held by AmbiguousRecordStore)
277
+ // as well as those found not to be ambiguous. The final act of this function will be to delete
278
+ // the disambiguation field from those records - it is only going to be there for the purpose
279
+ // of disambiguation, and should not be returned by our caller once disambiguation is complete.
280
+ //
281
+ // The scary-looking templating used here ensures that the objects in allRecords (and also
282
+ // ambiguousRecordStore) include an (optional) string property with the name identified by
283
+ // disambiguationField. For the avoidance of doubt, "prop" here could be anything - "foo in f"
284
+ // would achieve the same result.
285
+ disambiguate(allRecords, ambiguousRecordStore, disambiguationField, disambiguateItemCallback, completionCallback) {
286
+ const that = this;
287
+ async.map(Object.keys(ambiguousRecordStore), function (resourceName, cbm) {
288
+ const resource = that.getResource(resourceName);
289
+ const projection = that.generateListFieldProjection(resource);
290
+ resource.model
291
+ .find({ _id: { $in: ambiguousRecordStore[resourceName].map((sr) => sr[disambiguationField]) } })
292
+ .select(projection)
293
+ .lean()
294
+ .then((disambiguationRecs) => {
295
+ for (const ambiguousResult of ambiguousRecordStore[resourceName]) {
296
+ const disambiguator = disambiguationRecs.find((d) => d._id.toString() === ambiguousResult[disambiguationField].toString());
297
+ if (disambiguator) {
298
+ let suffix = "";
299
+ for (const listField in projection) {
300
+ if (disambiguator[listField]) {
301
+ if (suffix) {
302
+ suffix += " ";
303
+ }
304
+ suffix += disambiguator[listField];
305
+ }
306
+ }
307
+ if (suffix) {
308
+ disambiguateItemCallback(ambiguousResult, suffix);
309
+ }
310
+ }
311
+ }
312
+ cbm(null);
313
+ })
314
+ .catch((err) => {
315
+ cbm(err);
211
316
  });
212
- if (translation) {
213
- string = translation.to;
317
+ }, (err) => {
318
+ for (const record of allRecords) {
319
+ delete record[disambiguationField];
214
320
  }
215
- }
216
- return string;
321
+ completionCallback(err);
322
+ });
217
323
  }
218
- // return a string that determines the sort order of the resultObject
219
- function calcResultValue(obj) {
220
- function padLeft(score, reqLength, str) {
221
- if (str === void 0) { str = '0'; }
222
- return new Array(1 + reqLength - String(score).length).join(str) + score;
324
+ internalSearch(req, resourcesToSearch, includeResourceInResults, limit, callback) {
325
+ if (typeof req.query === 'undefined') {
326
+ req.query = {};
223
327
  }
224
- var sortString = '';
225
- sortString += padLeft(obj.addHits || 9, 1);
226
- sortString += padLeft(obj.searchImportance || 99, 2);
227
- sortString += padLeft(obj.weighting || 9999, 4);
228
- sortString += obj.text;
229
- return sortString;
230
- }
231
- if (filter) {
232
- filter = JSON.parse(filter);
233
- }
234
- for (var i = 0; i < resourceCount; i++) {
235
- var resource = resourcesToSearch[i];
236
- if (resourceCount === 1 || resource.options.searchImportance !== false) {
237
- var schema = resource.model.schema;
238
- var indexedFields = [];
239
- for (var j = 0; j < schema._indexes.length; j++) {
240
- var attributes = schema._indexes[j][0];
241
- var field = Object.keys(attributes)[0];
242
- if (indexedFields.indexOf(field) === -1) {
243
- indexedFields.push(field);
244
- }
245
- }
246
- for (var path in schema.paths) {
247
- if (path !== '_id' && schema.paths.hasOwnProperty(path)) {
248
- if (schema.paths[path]._index && !schema.paths[path].options.noSearch) {
249
- if (indexedFields.indexOf(path) === -1) {
250
- indexedFields.push(path);
328
+ const timestamps = { sentAt: req.query.sentAt, startedAt: new Date().valueOf(), completedAt: undefined };
329
+ let searches = [], resourceCount = resourcesToSearch.length, searchFor = req.query.q || '', filter = req.query.f;
330
+ function translate(string, array, context) {
331
+ if (array) {
332
+ let translation = _.find(array, function (fromTo) {
333
+ return fromTo.from === string && (!fromTo.context || fromTo.context === context);
334
+ });
335
+ if (translation) {
336
+ string = translation.to;
337
+ }
338
+ }
339
+ return string;
340
+ }
341
+ // return a string that determines the sort order of the resultObject
342
+ function calcResultValue(obj) {
343
+ function padLeft(score, reqLength, str = '0') {
344
+ return new Array(1 + reqLength - String(score).length).join(str) + score;
345
+ }
346
+ let sortString = '';
347
+ sortString += padLeft(obj.addHits || 9, 1);
348
+ sortString += padLeft(obj.searchImportance || 99, 2);
349
+ sortString += padLeft(obj.weighting || 9999, 4);
350
+ sortString += obj.text;
351
+ return sortString;
352
+ }
353
+ if (filter) {
354
+ filter = JSON.parse(filter);
355
+ }
356
+ // See if we are narrowing down the resources
357
+ let collectionName;
358
+ let collectionNameLower;
359
+ let colonPos = searchFor.indexOf(':');
360
+ switch (colonPos) {
361
+ case -1:
362
+ // Original behaviour = do nothing different
363
+ break;
364
+ case 0:
365
+ // "Special search" - yet to be implemented
366
+ break;
367
+ default:
368
+ collectionName = searchFor.slice(0, colonPos);
369
+ collectionNameLower = collectionName.toLowerCase();
370
+ searchFor = searchFor.slice(colonPos + 1, 999).trim();
371
+ if (searchFor === '') {
372
+ searchFor = '?';
373
+ }
374
+ break;
375
+ }
376
+ for (let i = 0; i < resourceCount; i++) {
377
+ let resource = resourcesToSearch[i];
378
+ if (resourceCount === 1 || (resource.options.searchImportance !== false && (!collectionName || collectionNameLower === resource.resourceNameLower || resource.options?.synonyms?.find(s => s.name === collectionNameLower)))) {
379
+ let schema = resource.model.schema;
380
+ let indexedFields = [];
381
+ for (let j = 0; j < schema._indexes.length; j++) {
382
+ let attributes = schema._indexes[j][0];
383
+ let field = Object.keys(attributes)[0];
384
+ if (indexedFields.indexOf(field) === -1) {
385
+ indexedFields.push(field);
386
+ }
387
+ }
388
+ for (let path in schema.paths) {
389
+ if (path !== '_id' && schema.paths.hasOwnProperty(path)) {
390
+ if (schema.paths[path]._index && !schema.paths[path].options.noSearch) {
391
+ if (indexedFields.indexOf(path) === -1) {
392
+ indexedFields.push(path);
393
+ }
251
394
  }
252
395
  }
253
396
  }
397
+ if (indexedFields.length === 0) {
398
+ console.log('ERROR: Searching on a collection with no indexes ' + resource.resourceName);
399
+ }
400
+ let synonymObj = resource.options?.synonyms?.find(s => s.name.toLowerCase() === collectionNameLower);
401
+ const synonymFilter = synonymObj?.filter;
402
+ for (let m = 0; m < indexedFields.length; m++) {
403
+ let searchObj = { resource: resource, field: indexedFields[m] };
404
+ if (synonymFilter) {
405
+ searchObj.filter = synonymFilter;
406
+ }
407
+ searches.push(searchObj);
408
+ }
254
409
  }
255
- if (indexedFields.length === 0) {
256
- console.log('ERROR: Searching on a collection with no indexes ' + resource.resourceName);
410
+ }
411
+ const that = this;
412
+ let results = [];
413
+ let moreCount = 0;
414
+ let searchCriteria;
415
+ let searchStrings;
416
+ let multiMatchPossible = false;
417
+ if (searchFor === '?') {
418
+ // interpret this as a wildcard (so there is no way to search for ?
419
+ searchCriteria = null;
420
+ }
421
+ else {
422
+ // Support for searching anywhere in a field by starting with *
423
+ let startAnchor = '^';
424
+ if (searchFor.slice(0, 1) === '*') {
425
+ startAnchor = '';
426
+ searchFor = searchFor.slice(1);
257
427
  }
258
- for (var m = 0; m < indexedFields.length; m++) {
259
- searches.push({ resource: resource, field: indexedFields[m] });
428
+ // THe snippet to escape the special characters comes from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
429
+ searchFor = searchFor.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
430
+ multiMatchPossible = searchFor.includes(' ');
431
+ if (multiMatchPossible) {
432
+ searchStrings = searchFor.split(' ');
260
433
  }
434
+ let modifiedSearchStr = multiMatchPossible ? searchStrings.join('|') : searchFor;
435
+ searchFor = searchFor.toLowerCase(); // For later case-insensitive comparison
436
+ // Removed the logic that preserved spaces when collection was specified because Louise asked me to.
437
+ searchCriteria = { $regex: `${startAnchor}(${modifiedSearchStr})`, $options: 'i' };
261
438
  }
262
- }
263
- var that = this;
264
- var results = [], moreCount = 0, searchCriteria, multiMatchPossible = searchFor.includes(' '), modifiedSearchStr = multiMatchPossible ? searchFor.split(' ').join('|') : searchFor;
265
- // Removed the logic that preserved spaces when collection was specified because Louise asked me to.
266
- searchCriteria = { $regex: '^(' + modifiedSearchStr + ')', $options: 'i' };
267
- var handleSearchResultsFromIndex = function (err, docs, item, cb) {
268
- if (!err && docs && docs.length > 0) {
269
- async.map(docs, function (aDoc, cbdoc) {
270
- // Do we already have them in the list?
271
- var thisId = aDoc._id.toString(), resultObject, resultPos;
439
+ let handleSearchResultsFromIndex = function (err, docs, item, cb) {
440
+ function handleSingleSearchResult(aDoc, cbdoc) {
441
+ let thisId = aDoc._id.toString(), resultObject, resultPos;
272
442
  function handleResultsInList() {
443
+ if (multiMatchPossible) {
444
+ resultObject.matched = resultObject.matched || [];
445
+ // record the index of string that matched, so we don't count it against another field
446
+ for (let i = 0; i < searchStrings.length; i++) {
447
+ if (aDoc[item.field].toLowerCase().indexOf(searchStrings[i]) === 0) {
448
+ resultObject.matched.push(i);
449
+ break;
450
+ }
451
+ }
452
+ }
273
453
  resultObject.searchImportance = item.resource.options.searchImportance || 99;
274
454
  if (item.resource.options.localisationData) {
275
455
  resultObject.resource = translate(resultObject.resource, item.resource.options.localisationData, "resource");
@@ -279,32 +459,57 @@ DataForm.prototype.internalSearch = function (req, resourcesToSearch, includeRes
279
459
  results.splice(_.sortedIndexBy(results, resultObject, calcResultValue), 0, resultObject);
280
460
  cbdoc(null);
281
461
  }
462
+ // Do we already have them in the list?
282
463
  for (resultPos = results.length - 1; resultPos >= 0; resultPos--) {
283
464
  if (results[resultPos].id.toString() === thisId) {
284
465
  break;
285
466
  }
286
467
  }
287
468
  if (resultPos >= 0) {
288
- resultObject = {};
289
- extend(resultObject, results[resultPos]);
469
+ resultObject = Object.assign({}, results[resultPos]);
290
470
  // If they have already matched then improve their weighting
291
- // TODO: if the search string is B F currently Benjamin Barker scores same as Benjamin Franklin)
292
471
  if (multiMatchPossible) {
293
- resultObject.addHits = Math.max((resultObject.addHits || 9) - 1, 1);
472
+ // record the index of string that matched, so we don't count it against another field
473
+ for (let i = 0; i < searchStrings.length; i++) {
474
+ if (!resultObject.matched.includes(i) && aDoc[item.field].toLowerCase().indexOf(searchStrings[i]) === 0) {
475
+ resultObject.matched.push(i);
476
+ resultObject.addHits = Math.max((resultObject.addHits || 9) - 1, 0);
477
+ // remove it from current position
478
+ results.splice(resultPos, 1);
479
+ // and re-insert where appropriate
480
+ results.splice(_.sortedIndexBy(results, resultObject, calcResultValue), 0, resultObject);
481
+ break;
482
+ }
483
+ }
294
484
  }
295
- // remove it from current position
296
- results.splice(resultPos, 1);
297
- // and re-insert where appropriate
298
- results.splice(_.sortedIndexBy(results, resultObject, calcResultValue), 0, resultObject);
299
485
  cbdoc(null);
300
486
  }
301
487
  else {
302
488
  // Otherwise add them new...
489
+ let addHits;
490
+ if (multiMatchPossible) {
491
+ // If they match the whole search phrase in one index they get smaller addHits (so they sort higher)
492
+ if (aDoc[item.field].toLowerCase().indexOf(searchFor) === 0) {
493
+ addHits = 7;
494
+ }
495
+ }
496
+ let disambiguationId;
497
+ const opts = item.resource.options;
498
+ const disambiguationResource = opts.disambiguation?.resource;
499
+ if (disambiguationResource) {
500
+ disambiguationId = aDoc[opts.disambiguation.field]?.toString();
501
+ }
303
502
  // Use special listings format if defined
304
- var specialListingFormat = item.resource.options.searchResultFormat;
503
+ let specialListingFormat = item.resource.options.searchResultFormat;
305
504
  if (specialListingFormat) {
306
- resultObject = specialListingFormat.apply(aDoc);
307
- handleResultsInList();
505
+ specialListingFormat.apply(aDoc, [req])
506
+ .then((resultObj) => {
507
+ resultObject = resultObj;
508
+ resultObject.addHits = addHits;
509
+ resultObject.disambiguationResource = disambiguationResource;
510
+ resultObject.disambiguationId = disambiguationId;
511
+ handleResultsInList();
512
+ });
308
513
  }
309
514
  else {
310
515
  that.getListFields(item.resource, aDoc, function (err, description) {
@@ -315,6 +520,9 @@ DataForm.prototype.internalSearch = function (req, resourcesToSearch, includeRes
315
520
  resultObject = {
316
521
  id: aDoc._id,
317
522
  weighting: 9999,
523
+ addHits,
524
+ disambiguationResource,
525
+ disambiguationId,
318
526
  text: description
319
527
  };
320
528
  if (resourceCount > 1 || includeResourceInResults) {
@@ -325,420 +533,667 @@ DataForm.prototype.internalSearch = function (req, resourcesToSearch, includeRes
325
533
  });
326
534
  }
327
535
  }
328
- }, function (err) {
536
+ }
537
+ if (!err && docs && docs.length > 0) {
538
+ async.map(docs, handleSingleSearchResult, cb);
539
+ }
540
+ else {
329
541
  cb(err);
330
- });
331
- }
332
- else {
333
- cb(err);
334
- }
335
- };
336
- this.searchFunc(searches, function (item, cb) {
337
- var searchDoc = {};
338
- if (filter) {
339
- that.hackVariables(filter);
340
- extend(searchDoc, filter);
341
- if (filter[item.field]) {
342
- delete searchDoc[item.field];
343
- var obj1 = {}, obj2 = {};
344
- obj1[item.field] = filter[item.field];
345
- obj2[item.field] = searchCriteria;
346
- searchDoc['$and'] = [obj1, obj2];
542
+ }
543
+ };
544
+ this.searchFunc(searches, function (item, cb) {
545
+ let searchDoc = {};
546
+ let searchFilter = filter || item.filter;
547
+ if (searchFilter) {
548
+ that.hackVariables(searchFilter);
549
+ extend(searchDoc, searchFilter);
550
+ if (searchFilter[item.field]) {
551
+ delete searchDoc[item.field];
552
+ let obj1 = {}, obj2 = {};
553
+ obj1[item.field] = searchFilter[item.field];
554
+ obj2[item.field] = searchCriteria;
555
+ searchDoc['$and'] = [obj1, obj2];
556
+ }
557
+ else {
558
+ if (searchCriteria) {
559
+ searchDoc[item.field] = searchCriteria;
560
+ }
561
+ }
347
562
  }
348
563
  else {
349
- searchDoc[item.field] = searchCriteria;
564
+ if (searchCriteria) {
565
+ searchDoc[item.field] = searchCriteria;
566
+ }
350
567
  }
351
- }
352
- else {
353
- searchDoc[item.field] = searchCriteria;
354
- }
355
- // The +60 in the next line is an arbitrary safety zone for situations where items that match the string
356
- // in more than one index get filtered out.
357
- // TODO : Figure out a better way to deal with this
358
- if (item.resource.options.searchFunc) {
359
- item.resource.options.searchFunc(item.resource, req, null, searchDoc, item.resource.options.searchOrder, limit + 60, null, function (err, docs) {
360
- handleSearchResultsFromIndex(err, docs, item, cb);
361
- });
362
- }
363
- else {
364
- that.filteredFind(item.resource, req, null, searchDoc, item.resource.options.searchOrder, limit + 60, null, function (err, docs) {
365
- handleSearchResultsFromIndex(err, docs, item, cb);
366
- });
367
- }
368
- }, function (err) {
369
- if (err) {
370
- callback(err);
371
- }
372
- else {
373
- // Strip weighting from the results
374
- results = _.map(results, function (aResult) {
375
- delete aResult.weighting;
376
- return aResult;
377
- });
378
- if (results.length > limit) {
379
- moreCount += results.length - limit;
380
- results.splice(limit);
568
+ /*
569
+ The +200 below line is an (imperfect) arbitrary safety zone for situations where items that match the string in more than one index get filtered out.
570
+ An example where it fails is searching for "e c" which fails to get a old record Emily Carpenter in a big dataset sorted by date last accessed as they
571
+ are not returned within the first 200 in forenames so don't get the additional hit score and languish outside the visible results, though those visible
572
+ results end up containing people who only match either c or e (but have been accessed much more recently).
573
+
574
+ Increasing the number would be a short term fix at the cost of slowing down the search.
575
+ */
576
+ // TODO : Figure out a better way to deal with this
577
+ if (item.resource.options.searchFunc) {
578
+ item.resource.options.searchFunc(item.resource, req, null, searchDoc, item.resource.options.searchOrder, limit ? limit + 200 : 0, null, function (err, docs) {
579
+ handleSearchResultsFromIndex(err, docs, item, cb);
580
+ });
381
581
  }
382
- callback(null, { results: results, moreCount: moreCount });
383
- }
384
- });
385
- };
386
- DataForm.prototype.wrapInternalSearch = function (req, res, resourcesToSearch, includeResourceInResults, limit) {
387
- this.internalSearch(req, resourcesToSearch, includeResourceInResults, limit, function (err, resultsObject) {
388
- if (err) {
389
- res.status(400, err);
390
- }
391
- else {
392
- res.send(resultsObject);
393
- }
394
- });
395
- };
396
- DataForm.prototype.search = function () {
397
- return _.bind(function (req, res, next) {
398
- if (!(req.resource = this.getResource(req.params.resourceName))) {
399
- return next();
400
- }
401
- this.wrapInternalSearch(req, res, [req.resource], false, 10);
402
- }, this);
403
- };
404
- DataForm.prototype.searchAll = function () {
405
- return _.bind(function (req, res) {
406
- this.wrapInternalSearch(req, res, this.resources, true, 10);
407
- }, this);
408
- };
409
- DataForm.prototype.models = function () {
410
- var that = this;
411
- return function (req, res) {
412
- // TODO: Make this less wasteful - we only need to send the resourceNames of the resources
413
- // Check for optional modelFilter and call it with the request and current list. Otherwise just return the list.
414
- res.send(that.options.modelFilter ? that.options.modelFilter.call(null, req, that.resources) : that.resources);
415
- };
416
- };
417
- DataForm.prototype.renderError = function (err, redirectUrl, req, res) {
418
- if (typeof err === 'string') {
419
- res.send(err);
420
- }
421
- else {
422
- res.send(err.message);
423
- }
424
- };
425
- DataForm.prototype.redirect = function (address, req, res) {
426
- res.send(address);
427
- };
428
- DataForm.prototype.applySchemaSubset = function (vanilla, schema) {
429
- var outPath;
430
- if (schema) {
431
- outPath = {};
432
- for (var fld in schema) {
433
- if (schema.hasOwnProperty(fld)) {
434
- if (!vanilla[fld]) {
435
- throw new Error('No such field as ' + fld + '. Is it part of a sub-doc? If so you need the bit before the period.');
436
- }
437
- outPath[fld] = vanilla[fld];
438
- if (vanilla[fld].schema) {
439
- outPath[fld].schema = this.applySchemaSubset(outPath[fld].schema, schema[fld].schema);
440
- }
441
- outPath[fld].options = outPath[fld].options || {};
442
- for (var override in schema[fld]) {
443
- if (schema[fld].hasOwnProperty(override)) {
444
- if (!outPath[fld].options.form) {
445
- outPath[fld].options.form = {};
582
+ else {
583
+ that.filteredFind(item.resource, req, null, searchDoc, null, item.resource.options.searchOrder, limit ? limit + 200 : 0, null, function (err, docs) {
584
+ handleSearchResultsFromIndex(err, docs, item, cb);
585
+ });
586
+ }
587
+ }, function (err) {
588
+ if (err) {
589
+ callback(err);
590
+ }
591
+ else {
592
+ // Strip weighting from the results
593
+ results = _.map(results, function (aResult) {
594
+ delete aResult.weighting;
595
+ return aResult;
596
+ });
597
+ if (limit && results.length > limit) {
598
+ moreCount += results.length - limit;
599
+ results.splice(limit);
600
+ }
601
+ that.disambiguate(results, that.buildMultiResourceAmbiguousRecordStore(results, ["text"], "disambiguationResource"), "disambiguationId", (item, disambiguationText) => {
602
+ item.text += ` (${disambiguationText})`;
603
+ }, (err) => {
604
+ if (err) {
605
+ callback(err);
606
+ }
607
+ else {
608
+ // the disambiguate() call will have deleted the disambiguationIds but we're responsible for
609
+ // the disambiguationResources, which we shouldn't be returning to the client
610
+ for (const result of results) {
611
+ delete result.disambiguationResource;
446
612
  }
447
- outPath[fld].options.form[override] = schema[fld][override];
613
+ timestamps.completedAt = new Date().valueOf();
614
+ callback(null, { results, moreCount, timestamps });
448
615
  }
449
- }
616
+ });
450
617
  }
451
- }
618
+ });
452
619
  }
453
- else {
454
- outPath = vanilla;
620
+ ;
621
+ wrapInternalSearch(req, res, resourcesToSearch, includeResourceInResults, limit) {
622
+ this.internalSearch(req, resourcesToSearch, includeResourceInResults, limit, function (err, resultsObject) {
623
+ if (err) {
624
+ res.status(400, err);
625
+ }
626
+ else {
627
+ res.send(resultsObject);
628
+ }
629
+ });
455
630
  }
456
- return outPath;
457
- };
458
- DataForm.prototype.preprocess = function (resource, paths, formSchema) {
459
- var outPath = {}, hiddenFields = [], listFields = [];
460
- if (resource && resource.options && resource.options.idIsList) {
461
- paths['_id'].options = paths['_id'].options || {};
462
- paths['_id'].options.list = resource.options.idIsList;
631
+ ;
632
+ search() {
633
+ return _.bind(function (req, res, next) {
634
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
635
+ return next();
636
+ }
637
+ this.wrapInternalSearch(req, res, [req.resource], false, 0);
638
+ }, this);
463
639
  }
464
- for (var element in paths) {
465
- if (paths.hasOwnProperty(element) && element !== '__v') {
466
- // check for schemas
467
- if (paths[element].schema) {
468
- var subSchemaInfo = this.preprocess(null, paths[element].schema.paths);
469
- outPath[element] = { schema: subSchemaInfo.paths };
470
- if (paths[element].options.form) {
471
- outPath[element].options = { form: extend(true, {}, paths[element].options.form) };
472
- }
640
+ ;
641
+ searchAll() {
642
+ return _.bind(function (req, res) {
643
+ this.wrapInternalSearch(req, res, this.resources, true, 10);
644
+ }, this);
645
+ }
646
+ ;
647
+ models() {
648
+ const that = this;
649
+ return function (req, res) {
650
+ // Check for optional modelFilter and call it with the request and current list. Otherwise just return the list.
651
+ let resources = that.options.modelFilter ? that.options.modelFilter.call(null, req, that.resources) : that.resources;
652
+ if (req.query?.resourceNamesOnly) {
653
+ resources = resources.map((r) => r.resourceName);
473
654
  }
474
- else {
475
- // check for arrays
476
- var realType = paths[element].caster ? paths[element].caster : paths[element];
477
- if (!realType.instance) {
478
- if (realType.options.type) {
479
- var type = realType.options.type(), typeType = typeof type;
480
- if (typeType === 'string') {
481
- realType.instance = (!isNaN(Date.parse(type))) ? 'Date' : 'String';
655
+ res.send(resources);
656
+ };
657
+ }
658
+ ;
659
+ renderError(err, redirectUrl, req, res) {
660
+ res.statusMessage = err?.message || err;
661
+ res.status(400).end(err?.message || err);
662
+ }
663
+ ;
664
+ redirect(address, req, res) {
665
+ res.send(address);
666
+ }
667
+ ;
668
+ applySchemaSubset(vanilla, schema) {
669
+ let outPath;
670
+ if (schema) {
671
+ outPath = {};
672
+ for (let fld in schema) {
673
+ if (schema.hasOwnProperty(fld)) {
674
+ if (vanilla[fld]) {
675
+ outPath[fld] = _.cloneDeep(vanilla[fld]);
676
+ if (vanilla[fld].schema) {
677
+ outPath[fld].schema = this.applySchemaSubset(outPath[fld].schema, schema[fld].schema);
678
+ }
679
+ }
680
+ else {
681
+ if (fld.slice(0, 8) === "_bespoke") {
682
+ outPath[fld] = {
683
+ "path": fld,
684
+ "instance": schema[fld]._type,
685
+ };
482
686
  }
483
687
  else {
484
- realType.instance = typeType;
688
+ throw new Error('No such field as ' + fld + '. Is it part of a sub-doc? If so you need the bit before the period.');
485
689
  }
486
690
  }
487
- }
488
- outPath[element] = extend(true, {}, paths[element]);
489
- if (paths[element].options.secure) {
490
- hiddenFields.push(element);
491
- }
492
- if (paths[element].options.match) {
493
- outPath[element].options.match = paths[element].options.match.source;
494
- }
495
- var schemaListInfo = paths[element].options.list;
496
- if (schemaListInfo) {
497
- var listFieldInfo = { field: element };
498
- if (typeof schemaListInfo === 'object' && Object.keys(schemaListInfo).length > 0) {
499
- listFieldInfo.params = schemaListInfo;
691
+ outPath[fld].options = outPath[fld].options || {};
692
+ for (const override in schema[fld]) {
693
+ if (schema[fld].hasOwnProperty(override)) {
694
+ if (override.slice(0, 1) !== '_') {
695
+ if (schema[fld].hasOwnProperty(override)) {
696
+ if (!outPath[fld].options.form) {
697
+ outPath[fld].options.form = {};
698
+ }
699
+ outPath[fld].options.form[override] = schema[fld][override];
700
+ }
701
+ }
702
+ }
500
703
  }
501
- listFields.push(listFieldInfo);
502
704
  }
503
705
  }
504
706
  }
505
- }
506
- outPath = this.applySchemaSubset(outPath, formSchema);
507
- var returnObj = { paths: outPath };
508
- if (hiddenFields.length > 0) {
509
- returnObj.hide = hiddenFields;
510
- }
511
- if (listFields.length > 0) {
512
- returnObj.listFields = listFields;
513
- }
514
- return returnObj;
515
- };
516
- DataForm.prototype.schema = function () {
517
- return _.bind(function (req, res) {
518
- if (!(req.resource = this.getResource(req.params.resourceName))) {
519
- return res.status(404).end();
520
- }
521
- var formSchema = null;
522
- if (req.params.formName) {
523
- formSchema = req.resource.model.schema.statics['form'](req.params.formName);
524
- }
525
- var paths = this.preprocess(req.resource, req.resource.model.schema.paths, formSchema).paths;
526
- res.send(paths);
527
- }, this);
528
- };
529
- DataForm.prototype.report = function () {
530
- return _.bind(function (req, res, next) {
531
- if (!(req.resource = this.getResource(req.params.resourceName))) {
532
- return next();
533
- }
534
- var self = this;
535
- if (typeof req.query === 'undefined') {
536
- req.query = {};
707
+ else {
708
+ outPath = vanilla;
537
709
  }
538
- var reportSchema;
539
- if (req.params.reportName) {
540
- reportSchema = req.resource.model.schema.statics['report'](req.params.reportName, req);
710
+ return outPath;
711
+ }
712
+ ;
713
+ preprocess(resource, paths, formName, formSchema) {
714
+ function processInternalObject(obj) {
715
+ return Object.keys(obj).reduce((acc, cur) => {
716
+ const curType = typeof obj[cur];
717
+ if (!['$', '_'].includes(cur.charAt(0)) && curType !== 'function') {
718
+ const val = obj[cur];
719
+ if (val) {
720
+ if (Array.isArray(val)) {
721
+ if (val.length > 0) {
722
+ acc[cur] = val;
723
+ }
724
+ }
725
+ else if (curType === 'object' && !(val instanceof Date) && !(val instanceof RegExp)) {
726
+ acc[cur] = processInternalObject(obj[cur]);
727
+ }
728
+ else {
729
+ acc[cur] = obj[cur];
730
+ }
731
+ }
732
+ }
733
+ return acc;
734
+ }, {});
541
735
  }
542
- else if (req.query.r) {
543
- switch (req.query.r[0]) {
544
- case '[':
545
- reportSchema = { pipeline: JSON.parse(req.query.r) };
546
- break;
547
- case '{':
548
- reportSchema = JSON.parse(req.query.r);
549
- break;
550
- default:
551
- return self.renderError(new Error('Invalid "r" parameter'), null, req, res, next);
552
- }
736
+ let outPath = {}, hiddenFields = [], listFields = [];
737
+ if (resource && resource.preprocessed && resource.preprocessed[formName || "__default"]) {
738
+ return resource.preprocessed[formName || "__default"].paths;
553
739
  }
554
740
  else {
555
- var fields = {};
556
- for (var key in req.resource.model.schema.paths) {
557
- if (req.resource.model.schema.paths.hasOwnProperty(key)) {
558
- if (key !== '__v' && !req.resource.model.schema.paths[key].options.secure) {
559
- if (key.indexOf('.') === -1) {
560
- fields[key] = 1;
741
+ if (resource && resource.options && resource.options.idIsList) {
742
+ paths['_id'].options = paths['_id'].options || {};
743
+ paths['_id'].options.list = resource.options.idIsList;
744
+ }
745
+ for (let element in paths) {
746
+ if (paths.hasOwnProperty(element) && element !== '__v') {
747
+ // check for schemas
748
+ if (paths[element].schema) {
749
+ let subSchemaInfo = this.preprocess(null, paths[element].schema.paths);
750
+ outPath[element] = { schema: subSchemaInfo.paths };
751
+ if (paths[element].options.form) {
752
+ outPath[element].options = { form: extend(true, {}, paths[element].options.form) };
753
+ }
754
+ // this provides support for entire nested schemas that wish to remain hidden
755
+ if (paths[element].options.secure) {
756
+ hiddenFields.push(element);
757
+ }
758
+ // to support hiding individual properties of nested schema would require us
759
+ // to do something with subSchemaInfo.hide here
760
+ }
761
+ else {
762
+ // check for arrays
763
+ let realType = paths[element].caster ? paths[element].caster : paths[element];
764
+ if (!realType.instance) {
765
+ if (realType.options.type) {
766
+ let type = realType.options.type(), typeType = typeof type;
767
+ if (typeType === 'string') {
768
+ realType.instance = (!isNaN(Date.parse(type))) ? 'Date' : 'String';
769
+ }
770
+ else {
771
+ realType.instance = typeType;
772
+ }
773
+ }
774
+ }
775
+ outPath[element] = processInternalObject(paths[element]);
776
+ if (paths[element].options.secure) {
777
+ hiddenFields.push(element);
778
+ }
779
+ if (paths[element].options.match) {
780
+ outPath[element].options.match = paths[element].options.match.source || paths[element].options.match;
781
+ }
782
+ let schemaListInfo = paths[element].options.list;
783
+ if (schemaListInfo) {
784
+ let listFieldInfo = { field: element };
785
+ if (typeof schemaListInfo === 'object' && Object.keys(schemaListInfo).length > 0) {
786
+ listFieldInfo.params = schemaListInfo;
787
+ }
788
+ listFields.push(listFieldInfo);
561
789
  }
562
790
  }
563
791
  }
564
792
  }
565
- reportSchema = {
566
- pipeline: [
567
- { $project: fields }
568
- ], drilldown: req.params.resourceName + '/|_id|/edit'
569
- };
570
- }
571
- // Replace parameters in pipeline
572
- var schemaCopy = {};
573
- extend(schemaCopy, reportSchema);
574
- schemaCopy.params = schemaCopy.params || [];
575
- self.reportInternal(req, req.resource, schemaCopy, function (err, result) {
576
- if (err) {
577
- self.renderError(err, null, req, res, next);
793
+ outPath = this.applySchemaSubset(outPath, formSchema);
794
+ let returnObj = { paths: outPath };
795
+ if (hiddenFields.length > 0) {
796
+ returnObj.hide = hiddenFields;
578
797
  }
579
- else {
580
- res.send(result);
798
+ if (listFields.length > 0) {
799
+ returnObj.listFields = listFields;
581
800
  }
582
- });
583
- }, this);
584
- };
585
- DataForm.prototype.hackVariablesInPipeline = function (runPipeline) {
586
- for (var pipelineSection = 0; pipelineSection < runPipeline.length; pipelineSection++) {
587
- if (runPipeline[pipelineSection]['$match']) {
588
- this.hackVariables(runPipeline[pipelineSection]['$match']);
801
+ if (resource) {
802
+ resource.preprocessed = resource.preprocessed || {};
803
+ resource.preprocessed[formName || "__default"] = returnObj;
804
+ }
805
+ return returnObj;
589
806
  }
590
807
  }
591
- };
592
- DataForm.prototype.hackVariables = function (obj) {
593
- // Replace variables that cannot be serialised / deserialised. Bit of a hack, but needs must...
594
- // Anything formatted 1800-01-01T00:00:00.000Z or 1800-01-01T00:00:00.000+0000 is converted to a Date
595
- // Only handles the cases I need for now
596
- // TODO: handle arrays etc
597
- for (var prop in obj) {
598
- if (obj.hasOwnProperty(prop)) {
599
- if (typeof obj[prop] === 'string') {
600
- var dateTest = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3})(Z|[+ -]\d{4})$/.exec(obj[prop]);
601
- if (dateTest) {
602
- obj[prop] = new Date(dateTest[1] + 'Z');
603
- }
604
- else {
605
- var objectIdTest = /^([0-9a-fA-F]{24})$/.exec(obj[prop]);
606
- if (objectIdTest) {
607
- obj[prop] = new this.mongoose.Types.ObjectId(objectIdTest[1]);
808
+ ;
809
+ schema() {
810
+ return _.bind(function (req, res) {
811
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
812
+ return res.status(404).end();
813
+ }
814
+ let formSchema = null;
815
+ const formName = req.params.formName;
816
+ if (req.resource.preprocessed?.[formName || "__default"]) {
817
+ res.send(req.resource.preprocessed[formName || "__default"].paths);
818
+ }
819
+ else {
820
+ if (formName) {
821
+ try {
822
+ formSchema = req.resource.model.schema.statics['form'](escapeHtml(formName), req);
823
+ }
824
+ catch (e) {
825
+ return res.status(404).send(e.message);
608
826
  }
609
827
  }
828
+ let paths = this.preprocess(req.resource, req.resource.model.schema.paths, formName, formSchema).paths;
829
+ res.send(paths);
610
830
  }
611
- else if (_.isObject(obj[prop])) {
612
- this.hackVariables(obj[prop]);
613
- }
614
- }
615
- }
616
- };
617
- DataForm.prototype.reportInternal = function (req, resource, schema, callback) {
618
- var runPipelineStr;
619
- var runPipelineObj;
620
- var self = this;
621
- if (typeof req.query === 'undefined') {
622
- req.query = {};
831
+ }, this);
623
832
  }
624
- self.doFindFunc(req, resource, function (err, queryObj) {
625
- if (err) {
626
- return 'There was a problem with the findFunc for model';
627
- }
628
- else {
629
- runPipelineStr = JSON.stringify(schema.pipeline);
630
- for (var param in req.query) {
631
- if (req.query[param]) {
632
- if (param !== 'r') { // we don't want to copy the whole report schema (again!)
633
- schema.params[param].value = req.query[param];
634
- }
833
+ ;
834
+ report() {
835
+ return _.bind(async function (req, res, next) {
836
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
837
+ return next();
838
+ }
839
+ const self = this;
840
+ if (typeof req.query === 'undefined') {
841
+ req.query = {};
842
+ }
843
+ let reportSchema;
844
+ if (req.params.reportName) {
845
+ reportSchema = await req.resource.model.schema.statics['report'](req.params.reportName, req);
846
+ }
847
+ else if (req.query.r) {
848
+ switch (req.query.r[0]) {
849
+ case '[':
850
+ reportSchema = { pipeline: JSON.parse(req.query.r) };
851
+ break;
852
+ case '{':
853
+ reportSchema = JSON.parse(req.query.r);
854
+ break;
855
+ default:
856
+ return self.renderError(new Error('Invalid "r" parameter'), null, req, res);
635
857
  }
636
858
  }
637
- // Replace parameters with the value
638
- if (runPipelineStr) {
639
- runPipelineStr = runPipelineStr.replace(/\"\(.+?\)\"/g, function (match) {
640
- var sparam = schema.params[match.slice(2, -2)];
641
- if (sparam.type === 'number') {
642
- return sparam.value;
643
- }
644
- else if (_.isObject(sparam.value)) {
645
- return JSON.stringify(sparam.value);
859
+ else {
860
+ let fields = {};
861
+ for (let key in req.resource.model.schema.paths) {
862
+ if (req.resource.model.schema.paths.hasOwnProperty(key)) {
863
+ if (key !== '__v' && !req.resource.model.schema.paths[key].options.secure) {
864
+ if (key.indexOf('.') === -1) {
865
+ fields[key] = 1;
866
+ }
867
+ }
646
868
  }
647
- else if (sparam.value[0] === '{') {
648
- return sparam.value;
869
+ }
870
+ reportSchema = {
871
+ pipeline: [
872
+ { $project: fields }
873
+ ], drilldown: req.params.resourceName + '/|_id|/edit'
874
+ };
875
+ }
876
+ // Replace parameters in pipeline
877
+ let schemaCopy = {};
878
+ extend(schemaCopy, reportSchema);
879
+ schemaCopy.params = schemaCopy.params || [];
880
+ self.reportInternal(req, req.resource, schemaCopy, function (err, result) {
881
+ if (err) {
882
+ res.send({ success: false, error: err.message || err });
883
+ }
884
+ else {
885
+ res.send(result);
886
+ }
887
+ });
888
+ }, this);
889
+ }
890
+ ;
891
+ hackVariablesInPipeline(runPipeline) {
892
+ for (let pipelineSection = 0; pipelineSection < runPipeline.length; pipelineSection++) {
893
+ if (runPipeline[pipelineSection]['$match']) {
894
+ this.hackVariables(runPipeline[pipelineSection]['$match']);
895
+ }
896
+ }
897
+ }
898
+ ;
899
+ hackVariables(obj) {
900
+ // Replace variables that cannot be serialised / deserialised. Bit of a hack, but needs must...
901
+ // Anything formatted 1800-01-01T00:00:00.000Z or 1800-01-01T00:00:00.000+0000 is converted to a Date
902
+ // Only handles the cases I need for now
903
+ // TODO: handle arrays etc
904
+ for (const prop in obj) {
905
+ if (obj.hasOwnProperty(prop)) {
906
+ if (typeof obj[prop] === 'string') {
907
+ const dateTest = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3})(Z|[+ -]\d{4})$/.exec(obj[prop]);
908
+ if (dateTest) {
909
+ obj[prop] = new Date(dateTest[1] + 'Z');
649
910
  }
650
- else {
651
- return '"' + sparam.value + '"';
911
+ else if (prop !== "$regex") {
912
+ const objectIdTest = /^([0-9a-fA-F]{24})$/.exec(obj[prop]);
913
+ if (objectIdTest) {
914
+ obj[prop] = new mongoose_1.Types.ObjectId(objectIdTest[1]);
915
+ }
652
916
  }
653
- });
917
+ }
918
+ else if (_.isObject(obj[prop])) {
919
+ this.hackVariables(obj[prop]);
920
+ }
654
921
  }
655
- // Don't send the 'secure' fields
656
- var hiddenFields = self.generateHiddenFields(resource, false);
657
- for (var hiddenField in hiddenFields) {
658
- if (hiddenFields.hasOwnProperty(hiddenField)) {
659
- if (runPipelineStr.indexOf(hiddenField) !== -1) {
660
- return callback('You cannot access ' + hiddenField);
661
- }
662
- }
663
- }
664
- runPipelineObj = JSON.parse(runPipelineStr);
665
- if (!_.isArray(runPipelineObj)) {
666
- runPipelineObj = [runPipelineObj];
667
- }
668
- self.hackVariablesInPipeline(runPipelineObj);
669
- // Add the findFunc query to the pipeline
670
- if (queryObj) {
671
- runPipelineObj.unshift({ $match: queryObj });
672
- }
673
- var toDo = {
674
- runAggregation: function (cb) {
675
- resource.model.aggregate(runPipelineObj, cb);
676
- }
677
- };
678
- var translations_1 = []; // array of form {ref:'lookupname',translations:[{value:xx, display:' '}]}
679
- // if we need to do any column translations add the function to the tasks list
680
- if (schema.columnTranslations) {
681
- toDo.applyTranslations = ['runAggregation', function (results, cb) {
682
- function doATranslate(column, theTranslation) {
683
- results['runAggregation'].forEach(function (resultRow) {
684
- var valToTranslate = resultRow[column.field];
685
- valToTranslate = (valToTranslate ? valToTranslate.toString() : '');
686
- var thisTranslation = _.find(theTranslation.translations, function (option) {
687
- return valToTranslate === option.value.toString();
688
- });
689
- resultRow[column.field] = thisTranslation ? thisTranslation.display : ' * Missing columnTranslation * ';
922
+ }
923
+ }
924
+ ;
925
+ async sanitisePipeline(aggregationParam, hiddenFields, findFuncQry, req) {
926
+ let that = this;
927
+ let array = Array.isArray(aggregationParam) ? aggregationParam : [aggregationParam];
928
+ let retVal = [];
929
+ let doneHiddenFields = false;
930
+ if (findFuncQry) {
931
+ retVal.unshift({ $match: findFuncQry });
932
+ }
933
+ for (let pipelineSection = 0; pipelineSection < array.length; pipelineSection++) {
934
+ let stage = array[pipelineSection];
935
+ let keys = Object.keys(stage);
936
+ if (keys.length !== 1) {
937
+ throw new Error('Invalid pipeline instruction');
938
+ }
939
+ switch (keys[0]) {
940
+ case '$project':
941
+ case '$addFields':
942
+ case '$count':
943
+ case "$group":
944
+ case "$limit":
945
+ case "$replaceRoot":
946
+ case "$replaceWith":
947
+ case "$sort":
948
+ case "$unwind":
949
+ // We don't care about these - they are all (as far as we know) safe
950
+ break;
951
+ case '$unionWith':
952
+ /*
953
+ Sanitise the pipeline we are doing a union with, removing hidden fields from that collection
954
+ */
955
+ if (!stage.$unionWith.coll) {
956
+ stage.$unionWith = { coll: stage.$unionWith, pipeline: [] };
957
+ }
958
+ const unionCollectionName = stage.$unionWith.coll;
959
+ const unionResource = that.getResourceFromCollection(unionCollectionName);
960
+ let unionHiddenLookupFields = {};
961
+ if (unionResource) {
962
+ if (unionResource.options?.hide?.length > 0) {
963
+ unionHiddenLookupFields = this.generateHiddenFields(unionResource, false);
964
+ }
965
+ }
966
+ stage.$unionWith.pipeline = await that.sanitisePipeline(stage.$unionWith.pipeline, unionHiddenLookupFields, findFuncQry, req);
967
+ break;
968
+ case '$match':
969
+ this.hackVariables(array[pipelineSection]['$match']);
970
+ retVal.push(array[pipelineSection]);
971
+ if (!doneHiddenFields && Object.keys(hiddenFields) && Object.keys(hiddenFields).length > 0) {
972
+ // We can now project out the hidden fields (we wait for the $match to make sure we don't break
973
+ // a select that uses a hidden field
974
+ retVal.push({ $project: hiddenFields });
975
+ doneHiddenFields = true;
976
+ }
977
+ stage = null;
978
+ break;
979
+ case '$lookup':
980
+ case '$graphLookup':
981
+ if (keys[0] === '$lookup') {
982
+ // For now at least, we only support simple $lookups with a single join field equality
983
+ let lookupProps = Object.keys(stage.$lookup);
984
+ if (lookupProps.length !== 4 || lookupProps.indexOf('from') === -1 || lookupProps.indexOf('localField') === -1 || lookupProps.indexOf('foreignField') === -1 || lookupProps.indexOf('as') === -1) {
985
+ throw new Error("No support for $lookup that isn't Equality Match with a Single Join Condition");
986
+ }
987
+ }
988
+ // hide any hiddenfields in the lookup collection
989
+ const collectionName = stage[keys[0]].from;
990
+ const lookupField = stage[keys[0]].as;
991
+ if ((collectionName + lookupField).indexOf('$') !== -1) {
992
+ throw new Error('No support for lookups where the "from" or "as" is anything other than a simple string');
993
+ }
994
+ const resource = that.getResourceFromCollection(collectionName);
995
+ if (resource) {
996
+ retVal.push(stage);
997
+ stage = null;
998
+ if (resource.options?.hide?.length > 0) {
999
+ const hiddenLookupFields = this.generateHiddenFields(resource, false);
1000
+ let hiddenFieldsObj = {};
1001
+ Object.keys(hiddenLookupFields).forEach(hf => {
1002
+ hiddenFieldsObj[`${lookupField}.${hf}`] = false;
690
1003
  });
1004
+ retVal.push({ $project: hiddenFieldsObj });
691
1005
  }
692
- schema.columnTranslations.forEach(function (columnTranslation) {
693
- if (columnTranslation.translations) {
694
- doATranslate(columnTranslation, columnTranslation);
1006
+ // Now we need to make sure that we restrict the lookup to documents we have access to
1007
+ if (resource.options.findFunc) {
1008
+ let allowNulls = false;
1009
+ // If the next stage is an $unwind
1010
+ let nextStageIsUnwind = false;
1011
+ if (array.length >= pipelineSection) {
1012
+ const nextStage = array[pipelineSection + 1];
1013
+ let nextKeys = Object.keys(nextStage);
1014
+ if (nextKeys.length !== 1) {
1015
+ throw new Error('Invalid pipeline instruction');
1016
+ }
1017
+ if (nextKeys[0] === '$unwind') {
1018
+ if (nextStage["$unwind"] === "$" + lookupField) {
1019
+ nextStageIsUnwind = true;
1020
+ }
1021
+ if (nextStage["$unwind"] && nextStage["$unwind"].path === "$" + lookupField) {
1022
+ nextStageIsUnwind = true;
1023
+ if (nextStage["$unwind"].preserveNullAndEmptyArrays) {
1024
+ allowNulls = true;
1025
+ }
1026
+ }
1027
+ }
695
1028
  }
696
- if (columnTranslation.ref) {
697
- var theTranslation = _.find(translations_1, function (translation) {
698
- return (translation.ref === columnTranslation.ref);
699
- });
700
- if (theTranslation) {
701
- doATranslate(columnTranslation, theTranslation);
1029
+ if (!nextStageIsUnwind) {
1030
+ throw new Error('No support for $lookup where the next stage is not an $unwind and the resources has a findFunc');
1031
+ }
1032
+ // Push the $unwind, add our own findFunc, and increment the pipelineStage counter
1033
+ retVal.push(array[pipelineSection + 1]);
1034
+ let lookedUpFindQry = await this.doFindFuncPromise(req, resource);
1035
+ if (lookedUpFindQry) {
1036
+ // Now we need to put the lookup base into the criteria
1037
+ for (const prop in lookedUpFindQry) {
1038
+ if (lookedUpFindQry.hasOwnProperty(prop)) {
1039
+ lookedUpFindQry[`${lookupField}.${prop}`] = lookedUpFindQry[prop];
1040
+ delete lookedUpFindQry[prop];
1041
+ }
1042
+ }
1043
+ if (allowNulls) {
1044
+ lookedUpFindQry = { $or: [lookedUpFindQry, { [lookupField]: { $exists: false } }] };
1045
+ }
1046
+ retVal.push({ $match: lookedUpFindQry });
1047
+ }
1048
+ pipelineSection++;
1049
+ }
1050
+ }
1051
+ break;
1052
+ default:
1053
+ // anything else is either known to be dangerous, not yet needed or we don't know what it is
1054
+ throw new Error('Unsupported pipeline instruction ' + keys[0]);
1055
+ }
1056
+ if (stage) {
1057
+ retVal.push(stage);
1058
+ }
1059
+ }
1060
+ if (!doneHiddenFields && Object.keys(hiddenFields) && Object.keys(hiddenFields).length > 0) {
1061
+ // If there was no $match we still need to hide the hidden fields
1062
+ retVal.unshift({ $project: hiddenFields });
1063
+ }
1064
+ return retVal;
1065
+ }
1066
+ reportInternal(req, resource, schema, callback) {
1067
+ let runPipelineStr;
1068
+ let runPipelineObj;
1069
+ let self = this;
1070
+ if (typeof req.query === 'undefined') {
1071
+ req.query = {};
1072
+ }
1073
+ self.doFindFunc(req, resource, function (err, queryObj) {
1074
+ if (err) {
1075
+ return 'There was a problem with the findFunc for model';
1076
+ }
1077
+ else {
1078
+ runPipelineStr = JSON.stringify(schema.pipeline);
1079
+ for (let param in req.query) {
1080
+ if (param !== 'noinput' && req.query.hasOwnProperty(param)) {
1081
+ if (req.query[param]) {
1082
+ if (param !== 'r') { // we don't want to copy the whole report schema (again!)
1083
+ if (schema.params[param] !== undefined) {
1084
+ schema.params[param].value = req.query[param];
702
1085
  }
703
1086
  else {
704
- cb('Invalid ref property of ' + columnTranslation.ref + ' in columnTranslations ' + columnTranslation.field);
1087
+ return callback(`No such parameter as ${param} - try one of ${Object.keys(schema.params).join()}`);
705
1088
  }
706
1089
  }
707
- });
708
- cb(null, null);
709
- }];
710
- var callFuncs = false;
711
- for (var i = 0; i < schema.columnTranslations.length; i++) {
712
- var thisColumnTranslation = schema.columnTranslations[i];
713
- if (thisColumnTranslation.field) {
714
- // if any of the column translations are adhoc funcs, set up the tasks to perform them
715
- if (thisColumnTranslation.fn) {
716
- callFuncs = true;
717
1090
  }
718
- // if this column translation is a "ref", set up the tasks to look up the values and populate the translations
719
- if (thisColumnTranslation.ref) {
720
- var lookup = self.getResource(thisColumnTranslation.ref);
721
- if (lookup) {
722
- if (!toDo[thisColumnTranslation.ref]) {
723
- var getFunc = function (ref) {
724
- var lookup = ref;
725
- return function (cb) {
726
- var translateObject = { ref: lookup.resourceName, translations: [] };
727
- translations_1.push(translateObject);
728
- lookup.model.find({}, {}, { lean: true }, function (err, findResults) {
729
- if (err) {
730
- cb(err);
731
- }
732
- else {
733
- // TODO - this ref func can probably be done away with now that list fields can have ref
734
- var j_1 = 0;
735
- async.whilst(function () {
736
- return j_1 < findResults.length;
1091
+ }
1092
+ }
1093
+ // Replace parameters with the value
1094
+ if (runPipelineStr) {
1095
+ runPipelineStr = runPipelineStr.replace(/"\(.+?\)"/g, function (match) {
1096
+ let sparam = schema.params[match.slice(2, -2)];
1097
+ if (sparam !== undefined) {
1098
+ if (sparam.type === 'number') {
1099
+ return sparam.value;
1100
+ }
1101
+ else if (_.isObject(sparam.value)) {
1102
+ return JSON.stringify(sparam.value);
1103
+ }
1104
+ else if (sparam.value[0] === '{') {
1105
+ return sparam.value;
1106
+ }
1107
+ else {
1108
+ return '"' + sparam.value + '"';
1109
+ }
1110
+ }
1111
+ else {
1112
+ return callback(`No such parameter as ${match.slice(2, -2)} - try one of ${Object.keys(schema.params).join()}`);
1113
+ }
1114
+ });
1115
+ }
1116
+ runPipelineObj = JSON.parse(runPipelineStr);
1117
+ let hiddenFields = self.generateHiddenFields(resource, false);
1118
+ let toDo = {
1119
+ runAggregation: function (cb) {
1120
+ self.sanitisePipeline(runPipelineObj, hiddenFields, queryObj, req)
1121
+ .then((runPipelineObj) => {
1122
+ resource.model.aggregate(runPipelineObj)
1123
+ .then((results) => {
1124
+ cb(null, results);
1125
+ })
1126
+ .catch((err) => {
1127
+ cb(err);
1128
+ });
1129
+ })
1130
+ .catch((err) => {
1131
+ throw new Error('Error in sanitisePipeline ' + err);
1132
+ });
1133
+ }
1134
+ };
1135
+ let translations = []; // array of form {ref:'lookupname',translations:[{value:xx, display:' '}]}
1136
+ // if we need to do any column translations add the function to the tasks list
1137
+ if (schema.columnTranslations) {
1138
+ toDo.applyTranslations = ['runAggregation', function (results, cb) {
1139
+ function doATranslate(column, theTranslation) {
1140
+ results['runAggregation'].forEach(function (resultRow) {
1141
+ let valToTranslate = resultRow[column.field];
1142
+ valToTranslate = (valToTranslate ? valToTranslate.toString() : '');
1143
+ let thisTranslation = _.find(theTranslation.translations, function (option) {
1144
+ return valToTranslate === option.value.toString();
1145
+ });
1146
+ resultRow[column.field] = thisTranslation ? thisTranslation.display : ' * Missing columnTranslation * ';
1147
+ });
1148
+ }
1149
+ schema.columnTranslations.forEach(function (columnTranslation) {
1150
+ if (columnTranslation.translations) {
1151
+ doATranslate(columnTranslation, columnTranslation);
1152
+ }
1153
+ if (columnTranslation.ref) {
1154
+ let theTranslation = _.find(translations, function (translation) {
1155
+ return (translation.ref === columnTranslation.ref);
1156
+ });
1157
+ if (theTranslation) {
1158
+ doATranslate(columnTranslation, theTranslation);
1159
+ }
1160
+ else {
1161
+ cb('Invalid ref property of ' + columnTranslation.ref + ' in columnTranslations ' + columnTranslation.field);
1162
+ }
1163
+ }
1164
+ });
1165
+ cb(null, null);
1166
+ }];
1167
+ let callFuncs = false;
1168
+ for (let i = 0; i < schema.columnTranslations.length; i++) {
1169
+ let thisColumnTranslation = schema.columnTranslations[i];
1170
+ if (thisColumnTranslation.field) {
1171
+ // if any of the column translations are adhoc funcs, set up the tasks to perform them
1172
+ if (thisColumnTranslation.fn) {
1173
+ callFuncs = true;
1174
+ }
1175
+ // if this column translation is a "ref", set up the tasks to look up the values and populate the translations
1176
+ if (thisColumnTranslation.ref) {
1177
+ let lookup = self.getResource(thisColumnTranslation.ref);
1178
+ if (lookup) {
1179
+ if (!toDo[thisColumnTranslation.ref]) {
1180
+ let getFunc = function (ref) {
1181
+ let lookup = ref;
1182
+ return function (cb) {
1183
+ let translateObject = { ref: lookup.resourceName, translations: [] };
1184
+ translations.push(translateObject);
1185
+ lookup.model.find({}, {})
1186
+ .lean()
1187
+ .exec()
1188
+ .then((findResults) => {
1189
+ let j = 0;
1190
+ async.whilst(function (cbtest) {
1191
+ cbtest(null, j < findResults.length);
737
1192
  }, function (cbres) {
738
- var theResult = findResults[j_1];
739
- translateObject.translations[j_1] = translateObject.translations[j_1] || {};
740
- var theTranslation = translateObject.translations[j_1];
741
- j_1++;
1193
+ let theResult = findResults[j];
1194
+ translateObject.translations[j] = translateObject.translations[j] || {};
1195
+ let theTranslation = translateObject.translations[j];
1196
+ j++;
742
1197
  self.getListFields(lookup, theResult, function (err, description) {
743
1198
  if (err) {
744
1199
  cbres(err);
@@ -750,78 +1205,72 @@ DataForm.prototype.reportInternal = function (req, resource, schema, callback) {
750
1205
  }
751
1206
  });
752
1207
  }, cb);
753
- }
754
- });
1208
+ })
1209
+ .catch((err) => {
1210
+ cb(err);
1211
+ });
1212
+ };
755
1213
  };
756
- };
757
- toDo[thisColumnTranslation.ref] = getFunc(lookup);
758
- toDo.applyTranslations.unshift(thisColumnTranslation.ref); // Make sure we populate lookup before doing translation
1214
+ toDo[thisColumnTranslation.ref] = getFunc(lookup);
1215
+ toDo.applyTranslations.unshift(thisColumnTranslation.ref); // Make sure we populate lookup before doing translation
1216
+ }
1217
+ }
1218
+ else {
1219
+ return callback('Invalid ref property of ' + thisColumnTranslation.ref + ' in columnTranslations ' + thisColumnTranslation.field);
759
1220
  }
760
1221
  }
761
- else {
762
- return callback('Invalid ref property of ' + thisColumnTranslation.ref + ' in columnTranslations ' + thisColumnTranslation.field);
1222
+ if (!thisColumnTranslation.translations && !thisColumnTranslation.ref && !thisColumnTranslation.fn) {
1223
+ return callback('A column translation needs a ref, fn or a translations property - ' + thisColumnTranslation.field + ' has neither');
763
1224
  }
764
1225
  }
765
- if (!thisColumnTranslation.translations && !thisColumnTranslation.ref && !thisColumnTranslation.fn) {
766
- return callback('A column translation needs a ref, fn or a translations property - ' + thisColumnTranslation.field + ' has neither');
1226
+ else {
1227
+ return callback('A column translation needs a field property');
767
1228
  }
768
1229
  }
769
- else {
770
- return callback('A column translation needs a field property');
771
- }
772
- }
773
- if (callFuncs) {
774
- toDo['callFunctions'] = ['runAggregation', function (results, cb) {
775
- async.each(results.runAggregation, function (row, cb) {
776
- for (var i = 0; i < schema.columnTranslations.length; i++) {
777
- var thisColumnTranslation = schema.columnTranslations[i];
778
- if (thisColumnTranslation.fn) {
779
- thisColumnTranslation.fn(row, cb);
1230
+ if (callFuncs) {
1231
+ toDo['callFunctions'] = ['runAggregation', function (results, cb) {
1232
+ async.each(results.runAggregation, function (row, cb) {
1233
+ for (let i = 0; i < schema.columnTranslations.length; i++) {
1234
+ let thisColumnTranslation = schema.columnTranslations[i];
1235
+ if (thisColumnTranslation.fn) {
1236
+ thisColumnTranslation.fn(row, cb);
1237
+ }
780
1238
  }
781
- }
782
- }, function () {
783
- cb(null);
784
- });
785
- }];
786
- toDo.applyTranslations.unshift('callFunctions'); // Make sure we do function before translating its result
787
- }
788
- }
789
- async.auto(toDo, function (err, results) {
790
- if (err) {
791
- callback(err);
792
- }
793
- else {
794
- // TODO: Could loop through schema.params and just send back the values
795
- callback(null, { success: true, schema: schema, report: results.runAggregation, paramsUsed: schema.params });
796
- }
797
- });
798
- }
799
- });
800
- };
801
- DataForm.prototype.saveAndRespond = function (req, res, hiddenFields) {
802
- function internalSave(doc) {
803
- doc.save(function (err, doc2) {
804
- if (err) {
805
- var err2 = { status: 'err' };
806
- if (!err.errors) {
807
- err2.message = err.message;
808
- }
809
- else {
810
- extend(err2, err);
811
- }
812
- if (debug) {
813
- console.log('Error saving record: ' + JSON.stringify(err2));
1239
+ }, function () {
1240
+ cb(null);
1241
+ });
1242
+ }];
1243
+ toDo.applyTranslations.unshift('callFunctions'); // Make sure we do function before translating its result
1244
+ }
814
1245
  }
815
- res.status(400).send(err2);
1246
+ async.auto(toDo, function (err, results) {
1247
+ if (err) {
1248
+ callback(err);
1249
+ }
1250
+ else {
1251
+ callback(null, {
1252
+ success: true,
1253
+ schema: schema,
1254
+ report: results.runAggregation,
1255
+ paramsUsed: schema.params
1256
+ });
1257
+ }
1258
+ });
816
1259
  }
817
- else {
818
- doc2 = doc2.toObject();
819
- for (var hiddenField in hiddenFields) {
1260
+ });
1261
+ }
1262
+ ;
1263
+ saveAndRespond(req, res, hiddenFields) {
1264
+ function internalSave(doc) {
1265
+ doc.save()
1266
+ .then((saved) => {
1267
+ saved = saved.toObject();
1268
+ for (const hiddenField in hiddenFields) {
820
1269
  if (hiddenFields.hasOwnProperty(hiddenField) && hiddenFields[hiddenField]) {
821
- var parts = hiddenField.split('.');
822
- var lastPart = parts.length - 1;
823
- var target = doc2;
824
- for (var i = 0; i < lastPart; i++) {
1270
+ let parts = hiddenField.split('.');
1271
+ let lastPart = parts.length - 1;
1272
+ let target = saved;
1273
+ for (let i = 0; i < lastPart; i++) {
825
1274
  if (target.hasOwnProperty(parts[i])) {
826
1275
  target = target[parts[i]];
827
1276
  }
@@ -831,277 +1280,220 @@ DataForm.prototype.saveAndRespond = function (req, res, hiddenFields) {
831
1280
  }
832
1281
  }
833
1282
  }
834
- res.send(doc2);
835
- }
836
- });
837
- }
838
- var doc = req.doc;
839
- if (typeof req.resource.options.onSave === 'function') {
840
- req.resource.options.onSave(doc, req, function (err) {
841
- if (err) {
842
- throw err;
843
- }
844
- internalSave(doc);
845
- });
846
- }
847
- else {
848
- internalSave(doc);
849
- }
850
- };
851
- /**
852
- * All entities REST functions have to go through this first.
853
- */
854
- DataForm.prototype.processCollection = function (req) {
855
- req.resource = this.getResource(req.params.resourceName);
856
- };
857
- /**
858
- * Renders a view with the list of docs, which may be modified by query parameters
859
- */
860
- DataForm.prototype.collectionGet = function () {
861
- return _.bind(function (req, res, next) {
862
- this.processCollection(req);
863
- if (!req.resource) {
864
- return next();
865
- }
866
- if (typeof req.query === 'undefined') {
867
- req.query = {};
868
- }
869
- try {
870
- var aggregationParam = req.query.a ? JSON.parse(req.query.a) : null;
871
- var findParam = req.query.f ? JSON.parse(req.query.f) : {};
872
- var limitParam = req.query.l ? JSON.parse(req.query.l) : 0;
873
- var skipParam = req.query.s ? JSON.parse(req.query.s) : 0;
874
- var orderParam = req.query.o ? JSON.parse(req.query.o) : req.resource.options.listOrder;
875
- // Dates in aggregation must be Dates
876
- if (aggregationParam) {
877
- this.hackVariablesInPipeline(aggregationParam);
878
- }
879
- var self_1 = this;
880
- this.filteredFind(req.resource, req, aggregationParam, findParam, orderParam, limitParam, skipParam, function (err, docs) {
881
- if (err) {
882
- return self_1.renderError(err, null, req, res, next);
1283
+ res.send(saved);
1284
+ })
1285
+ .catch((err) => {
1286
+ let err2 = { status: 'err' };
1287
+ if (!err.errors) {
1288
+ err2.message = err.message;
883
1289
  }
884
1290
  else {
885
- res.send(docs);
1291
+ extend(err2, err);
1292
+ }
1293
+ if (debug) {
1294
+ console.log('Error saving record: ' + JSON.stringify(err2));
886
1295
  }
1296
+ res.status(400).send(err2);
887
1297
  });
888
1298
  }
889
- catch (e) {
890
- res.send(e);
891
- }
892
- }, this);
893
- };
894
- DataForm.prototype.doFindFunc = function (req, resource, cb) {
895
- if (resource.options.findFunc) {
896
- resource.options.findFunc(req, cb);
897
- }
898
- else {
899
- cb(null);
900
- }
901
- };
902
- DataForm.prototype.filteredFind = function (resource, req, aggregationParam, findParam, sortOrder, limit, skip, callback) {
903
- var that = this;
904
- var hiddenFields = this.generateHiddenFields(resource, false);
905
- var stashAggregationResults;
906
- function doAggregation(cb) {
907
- if (aggregationParam) {
908
- resource.model.aggregate(aggregationParam, function (err, aggregationResults) {
1299
+ let doc = req.doc;
1300
+ if (typeof req.resource.options.onSave === 'function') {
1301
+ req.resource.options.onSave(doc, req, function (err) {
909
1302
  if (err) {
910
1303
  throw err;
911
1304
  }
912
- else {
913
- stashAggregationResults = aggregationResults;
914
- cb(_.map(aggregationResults, function (obj) {
915
- return obj._id;
916
- }));
917
- }
1305
+ internalSave(doc);
918
1306
  });
919
1307
  }
920
1308
  else {
921
- cb([]);
1309
+ internalSave(doc);
922
1310
  }
923
1311
  }
924
- doAggregation(function (idArray) {
925
- if (aggregationParam && idArray.length === 0) {
926
- callback(null, []);
1312
+ ;
1313
+ /**
1314
+ * All entities REST functions have to go through this first.
1315
+ */
1316
+ processCollection(req) {
1317
+ req.resource = this.getResource(req.params.resourceName);
1318
+ }
1319
+ ;
1320
+ /**
1321
+ * Renders a view with the list of docs, which may be modified by query parameters
1322
+ */
1323
+ collectionGet() {
1324
+ return _.bind(function (req, res, next) {
1325
+ this.processCollection(req);
1326
+ if (!req.resource) {
1327
+ return next();
1328
+ }
1329
+ if (typeof req.query === 'undefined') {
1330
+ req.query = {};
1331
+ }
1332
+ try {
1333
+ const aggregationParam = req.query.a ? JSON.parse(req.query.a) : null;
1334
+ const findParam = req.query.f ? JSON.parse(req.query.f) : {};
1335
+ const projectParam = req.query.p ? JSON.parse(req.query.p) : {};
1336
+ const limitParam = req.query.l ? JSON.parse(req.query.l) : 0;
1337
+ const skipParam = req.query.s ? JSON.parse(req.query.s) : 0;
1338
+ const orderParam = req.query.o ? JSON.parse(req.query.o) : req.resource.options.listOrder;
1339
+ // Dates in aggregation must be Dates
1340
+ if (aggregationParam) {
1341
+ this.hackVariablesInPipeline(aggregationParam);
1342
+ }
1343
+ const self = this;
1344
+ this.filteredFind(req.resource, req, aggregationParam, findParam, projectParam, orderParam, limitParam, skipParam, function (err, docs) {
1345
+ if (err) {
1346
+ return self.renderError(err, null, req, res);
1347
+ }
1348
+ else {
1349
+ res.send(docs);
1350
+ }
1351
+ });
1352
+ }
1353
+ catch (e) {
1354
+ res.status(400).send(e.message);
1355
+ }
1356
+ }, this);
1357
+ }
1358
+ ;
1359
+ generateProjection(hiddenFields, projectParam) {
1360
+ let type;
1361
+ function setSelectType(typeChar, checkChar) {
1362
+ if (type === checkChar) {
1363
+ throw new Error('Cannot mix include and exclude fields in select');
1364
+ }
1365
+ else {
1366
+ type = typeChar;
1367
+ }
927
1368
  }
928
- else {
929
- that.doFindFunc(req, resource, function (err, queryObj) {
930
- if (err) {
931
- callback(err);
1369
+ let retVal = hiddenFields;
1370
+ if (projectParam) {
1371
+ let projection = Object.keys(projectParam);
1372
+ if (projection.length > 0) {
1373
+ projection.forEach(p => {
1374
+ if (projectParam[p] === 0) {
1375
+ setSelectType('E', 'I');
1376
+ }
1377
+ else if (projectParam[p] === 1) {
1378
+ setSelectType('I', 'E');
1379
+ }
1380
+ else {
1381
+ throw new Error('Invalid projection: ' + projectParam);
1382
+ }
1383
+ });
1384
+ if (type && type === 'E') {
1385
+ // We are excluding fields - can just merge with hiddenFields
1386
+ Object.assign(retVal, projectParam, hiddenFields);
932
1387
  }
933
1388
  else {
934
- var query = resource.model.find(queryObj);
935
- if (idArray.length > 0) {
936
- query = query.where('_id').in(idArray);
937
- }
938
- query = query.find(findParam).select(hiddenFields);
939
- if (limit) {
940
- query = query.limit(limit);
941
- }
942
- if (skip) {
943
- query = query.skip(skip);
944
- }
945
- if (sortOrder) {
946
- query = query.sort(sortOrder);
947
- }
948
- query.exec(function (err, docs) {
949
- if (!err && stashAggregationResults) {
950
- docs.forEach(function (obj) {
951
- // Add any fields from the aggregation results whose field name starts __ to the mongoose Document
952
- var aggObj = stashAggregationResults.find(function (a) { return a._id.toString() === obj._id.toString(); });
953
- Object.keys(aggObj).forEach(function (k) {
954
- if (k.slice(0, 2) === '__') {
955
- obj[k] = aggObj[k];
956
- }
957
- });
958
- });
1389
+ // We are selecting fields - make sure none are hidden
1390
+ retVal = projectParam;
1391
+ for (let h in hiddenFields) {
1392
+ if (hiddenFields.hasOwnProperty(h)) {
1393
+ delete retVal[h];
959
1394
  }
960
- callback(err, docs);
961
- });
1395
+ }
962
1396
  }
963
- });
964
- }
965
- });
966
- };
967
- DataForm.prototype.collectionPost = function () {
968
- return _.bind(function (req, res, next) {
969
- this.processCollection(req);
970
- if (!req.resource) {
971
- next();
972
- return;
973
- }
974
- if (!req.body) {
975
- throw new Error('Nothing submitted.');
1397
+ }
976
1398
  }
977
- var cleansedBody = this.cleanseRequest(req);
978
- req.doc = new req.resource.model(cleansedBody);
979
- this.saveAndRespond(req, res);
980
- }, this);
981
- };
982
- /**
983
- * Generate an object of fields to not expose
984
- **/
985
- DataForm.prototype.generateHiddenFields = function (resource, state) {
986
- var hiddenFields = {};
987
- if (resource.options['hide'] !== undefined) {
988
- resource.options.hide.forEach(function (dt) {
989
- hiddenFields[dt] = state;
990
- });
1399
+ return retVal;
991
1400
  }
992
- return hiddenFields;
993
- };
994
- /** Sec issue
995
- * Cleanse incoming data to avoid overwrite and POST request forgery
996
- * (name may seem weird but it was in French, so it is some small improvement!)
997
- */
998
- DataForm.prototype.cleanseRequest = function (req) {
999
- var reqData = req.body, resource = req.resource;
1000
- delete reqData.__v; // Don't mess with Mongoose internal field (https://github.com/LearnBoost/mongoose/issues/1933)
1001
- if (typeof resource.options['hide'] === 'undefined') {
1002
- return reqData;
1003
- }
1004
- var hiddenFields = resource.options.hide;
1005
- _.each(reqData, function (num, key) {
1006
- _.each(hiddenFields, function (fi) {
1007
- if (fi === key) {
1008
- delete reqData[key];
1009
- }
1010
- });
1011
- });
1012
- return reqData;
1013
- };
1014
- DataForm.prototype.generateQueryForEntity = function (req, resource, id, cb) {
1015
- var hiddenFields = this.generateHiddenFields(resource, false);
1016
- hiddenFields.__v = 0;
1017
- this.doFindFunc(req, resource, function (err, queryObj) {
1018
- if (err) {
1019
- cb(err);
1401
+ ;
1402
+ doFindFunc(req, resource, cb) {
1403
+ if (resource.options.findFunc) {
1404
+ resource.options.findFunc(req, cb);
1020
1405
  }
1021
1406
  else {
1022
- var idSel = { _id: id };
1023
- var crit = queryObj ? extend(queryObj, idSel) : idSel;
1024
- cb(null, resource.model.findOne(crit).select(hiddenFields));
1407
+ cb(null);
1025
1408
  }
1026
- });
1027
- };
1028
- /*
1029
- * Entity request goes there first
1030
- * It retrieves the resource
1031
- */
1032
- DataForm.prototype.processEntity = function (req, res, next) {
1033
- if (!(req.resource = this.getResource(req.params.resourceName))) {
1034
- next();
1035
- return;
1036
1409
  }
1037
- this.generateQueryForEntity(req, req.resource, req.params.id, function (err, query) {
1038
- if (err) {
1039
- return res.send({
1040
- success: false,
1041
- err: util.inspect(err)
1042
- });
1043
- }
1044
- else {
1045
- query.exec(function (err, doc) {
1410
+ ;
1411
+ async doFindFuncPromise(req, resource) {
1412
+ return new Promise((resolve, reject) => {
1413
+ this.doFindFunc(req, resource, (err, queryObj) => {
1046
1414
  if (err) {
1047
- return res.send({
1048
- success: false,
1049
- err: util.inspect(err)
1050
- });
1415
+ reject(err);
1051
1416
  }
1052
- else if (doc == null) {
1053
- return res.send({
1054
- success: false,
1055
- err: 'Record not found'
1056
- });
1417
+ else {
1418
+ resolve(queryObj);
1057
1419
  }
1058
- req.doc = doc;
1059
- next();
1060
1420
  });
1061
- }
1062
- });
1063
- };
1064
- /**
1065
- * Gets a single entity
1066
- *
1067
- * @return {Function} The function to use as route
1068
- */
1069
- DataForm.prototype.entityGet = function () {
1070
- return _.bind(function (req, res, next) {
1071
- this.processEntity(req, res, function () {
1072
- if (!req.resource) {
1073
- return next();
1074
- }
1075
- if (req.resource.options.onAccess) {
1076
- req.resource.options.onAccess(req, function () {
1077
- return res.send(req.doc);
1421
+ });
1422
+ }
1423
+ ;
1424
+ async filteredFind(resource, req, aggregationParam, findParam, projectParam, sortOrder, limit, skip, callback) {
1425
+ const that = this;
1426
+ let hiddenFields = this.generateHiddenFields(resource, false);
1427
+ let stashAggregationResults;
1428
+ async function doAggregation(queryObj, cb) {
1429
+ if (aggregationParam) {
1430
+ aggregationParam = await that.sanitisePipeline(aggregationParam, hiddenFields, queryObj, req);
1431
+ resource.model.aggregate(aggregationParam)
1432
+ .then((aggregationResults) => {
1433
+ stashAggregationResults = aggregationResults;
1434
+ cb(_.map(aggregationResults, function (obj) {
1435
+ return obj._id;
1436
+ }));
1437
+ }).catch((err) => {
1438
+ throw err;
1078
1439
  });
1079
1440
  }
1080
1441
  else {
1081
- return res.send(req.doc);
1442
+ cb([]);
1082
1443
  }
1083
- });
1084
- }, this);
1085
- };
1086
- DataForm.prototype.replaceHiddenFields = function (record, data) {
1087
- var self = this;
1088
- if (record) {
1089
- record._replacingHiddenFields = true;
1090
- _.each(data, function (value, name) {
1091
- if (_.isObject(value)) {
1092
- self.replaceHiddenFields(record[name], value);
1444
+ }
1445
+ that.doFindFunc(req, resource, function (err, queryObj) {
1446
+ if (err) {
1447
+ callback(err);
1093
1448
  }
1094
1449
  else {
1095
- record[name] = value;
1450
+ doAggregation(queryObj, function (idArray) {
1451
+ if (aggregationParam && idArray.length === 0) {
1452
+ callback(null, []);
1453
+ }
1454
+ else {
1455
+ let query = resource.model.find(queryObj);
1456
+ if (idArray.length > 0) {
1457
+ query = query.where('_id').in(idArray);
1458
+ }
1459
+ if (findParam) {
1460
+ query = query.find(findParam);
1461
+ }
1462
+ query = query.select(that.generateProjection(hiddenFields, projectParam));
1463
+ if (limit) {
1464
+ query = query.limit(limit);
1465
+ }
1466
+ if (skip) {
1467
+ query = query.skip(skip);
1468
+ }
1469
+ if (sortOrder) {
1470
+ query = query.sort(sortOrder);
1471
+ }
1472
+ query.exec()
1473
+ .then((docs) => {
1474
+ if (stashAggregationResults) {
1475
+ for (const obj of docs) {
1476
+ // Add any fields from the aggregation results whose field name starts __ to the mongoose Document
1477
+ let aggObj = stashAggregationResults.find(a => a._id.toString() === obj._id.toString());
1478
+ for (const k of Object.keys(aggObj).filter((k) => k.startsWith('__'))) {
1479
+ obj[k] = aggObj[k];
1480
+ }
1481
+ }
1482
+ }
1483
+ callback(null, docs);
1484
+ })
1485
+ .catch((err) => {
1486
+ callback(err);
1487
+ });
1488
+ }
1489
+ });
1096
1490
  }
1097
1491
  });
1098
- delete record._replacingHiddenFields;
1099
1492
  }
1100
- };
1101
- DataForm.prototype.entityPut = function () {
1102
- return _.bind(function (req, res, next) {
1103
- var that = this;
1104
- this.processEntity(req, res, function () {
1493
+ ;
1494
+ collectionPost() {
1495
+ return _.bind(function (req, res, next) {
1496
+ this.processCollection(req);
1105
1497
  if (!req.resource) {
1106
1498
  next();
1107
1499
  return;
@@ -1109,70 +1501,509 @@ DataForm.prototype.entityPut = function () {
1109
1501
  if (!req.body) {
1110
1502
  throw new Error('Nothing submitted.');
1111
1503
  }
1112
- var cleansedBody = that.cleanseRequest(req);
1113
- // Merge
1114
- _.each(cleansedBody, function (value, name) {
1115
- req.doc[name] = (value === '') ? undefined : value;
1504
+ let cleansedBody = this.cleanseRequest(req);
1505
+ req.doc = new req.resource.model(cleansedBody);
1506
+ this.saveAndRespond(req, res);
1507
+ }, this);
1508
+ }
1509
+ ;
1510
+ /**
1511
+ * Generate an object of fields to not expose
1512
+ **/
1513
+ generateHiddenFields(resource, state) {
1514
+ let hiddenFields = {};
1515
+ if (resource.options['hide'] !== undefined) {
1516
+ resource.options.hide.forEach(function (dt) {
1517
+ hiddenFields[dt] = state;
1116
1518
  });
1117
- if (req.resource.options.hide !== undefined) {
1118
- var hiddenFields_1 = that.generateHiddenFields(req.resource, true);
1119
- hiddenFields_1._id = false;
1120
- req.resource.model.findById(req.doc._id, hiddenFields_1, { lean: true }, function (err, data) {
1121
- that.replaceHiddenFields(req.doc, data);
1122
- that.saveAndRespond(req, res, hiddenFields_1);
1519
+ }
1520
+ return hiddenFields;
1521
+ }
1522
+ ;
1523
+ /** Sec issue
1524
+ * Cleanse incoming data to avoid overwrite and POST request forgery
1525
+ * (name may seem weird but it was in French, so it is some small improvement!)
1526
+ */
1527
+ cleanseRequest(req) {
1528
+ let reqData = req.body, resource = req.resource;
1529
+ delete reqData.__v; // Don't mess with Mongoose internal field (https://github.com/LearnBoost/mongoose/issues/1933)
1530
+ if (typeof resource.options['hide'] === 'undefined') {
1531
+ return reqData;
1532
+ }
1533
+ let hiddenFields = resource.options.hide;
1534
+ _.each(reqData, function (num, key) {
1535
+ _.each(hiddenFields, function (fi) {
1536
+ if (fi === key) {
1537
+ delete reqData[key];
1538
+ }
1539
+ });
1540
+ });
1541
+ return reqData;
1542
+ }
1543
+ ;
1544
+ generateQueryForEntity(req, resource, id, cb) {
1545
+ let that = this;
1546
+ let hiddenFields = this.generateHiddenFields(resource, false);
1547
+ hiddenFields.__v = false;
1548
+ that.doFindFunc(req, resource, function (err, queryObj) {
1549
+ if (err) {
1550
+ cb(err);
1551
+ }
1552
+ else {
1553
+ const idSel = { _id: id };
1554
+ let crit;
1555
+ if (queryObj) {
1556
+ if (queryObj._id) {
1557
+ crit = { $and: [idSel, { _id: queryObj._id }] };
1558
+ delete queryObj._id;
1559
+ if (Object.keys(queryObj).length > 0) {
1560
+ crit = extend(crit, queryObj);
1561
+ }
1562
+ }
1563
+ else {
1564
+ crit = extend(queryObj, idSel);
1565
+ }
1566
+ }
1567
+ else {
1568
+ crit = idSel;
1569
+ }
1570
+ cb(null, resource.model.findOne(crit).select(that.generateProjection(hiddenFields, req.query?.p)));
1571
+ }
1572
+ });
1573
+ }
1574
+ ;
1575
+ /*
1576
+ * Entity request goes here first
1577
+ * It retrieves the resource
1578
+ */
1579
+ processEntity(req, res, next) {
1580
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
1581
+ return next();
1582
+ }
1583
+ this.generateQueryForEntity(req, req.resource, req.params.id, function (err, query) {
1584
+ if (err) {
1585
+ return res.status(500).send({
1586
+ success: false,
1587
+ err: util.inspect(err)
1123
1588
  });
1124
1589
  }
1125
1590
  else {
1126
- that.saveAndRespond(req, res);
1591
+ query.exec()
1592
+ .then((doc) => {
1593
+ if (doc) {
1594
+ req.doc = doc;
1595
+ return next();
1596
+ }
1597
+ else {
1598
+ return res.status(404).send({
1599
+ success: false,
1600
+ err: 'Record not found'
1601
+ });
1602
+ }
1603
+ })
1604
+ .catch((err) => {
1605
+ return res.status(400).send({
1606
+ success: false,
1607
+ err: util.inspect(err)
1608
+ });
1609
+ });
1127
1610
  }
1128
1611
  });
1129
- }, this);
1130
- };
1131
- DataForm.prototype.entityDelete = function () {
1132
- return _.bind(function (req, res, next) {
1133
- function internalRemove(doc) {
1134
- doc.remove(function (err) {
1135
- if (err) {
1136
- return res.send({ success: false });
1612
+ }
1613
+ ;
1614
+ /**
1615
+ * Gets a single entity
1616
+ *
1617
+ * @return {Function} The function to use as route
1618
+ */
1619
+ entityGet() {
1620
+ return _.bind(function (req, res, next) {
1621
+ this.processEntity(req, res, function () {
1622
+ if (!req.resource) {
1623
+ return next();
1624
+ }
1625
+ if (req.resource.options.onAccess) {
1626
+ req.resource.options.onAccess(req, function () {
1627
+ return res.status(200).send(req.doc);
1628
+ });
1629
+ }
1630
+ else {
1631
+ return res.status(200).send(req.doc);
1632
+ }
1633
+ });
1634
+ }, this);
1635
+ }
1636
+ ;
1637
+ replaceHiddenFields(record, data) {
1638
+ const self = this;
1639
+ if (record) {
1640
+ record._replacingHiddenFields = true;
1641
+ _.each(data, function (value, name) {
1642
+ if (_.isObject(value) && !Array.isArray(value)) {
1643
+ self.replaceHiddenFields(record[name], value);
1644
+ }
1645
+ else if (!record[name]) {
1646
+ record[name] = value;
1137
1647
  }
1138
- return res.send({ success: true });
1139
1648
  });
1649
+ delete record._replacingHiddenFields;
1140
1650
  }
1141
- this.processEntity(req, res, function () {
1142
- if (!req.resource) {
1143
- next();
1144
- return;
1651
+ }
1652
+ ;
1653
+ entityPut() {
1654
+ return _.bind(function (req, res, next) {
1655
+ const that = this;
1656
+ this.processEntity(req, res, function () {
1657
+ if (!req.resource) {
1658
+ next();
1659
+ return;
1660
+ }
1661
+ if (!req.body) {
1662
+ throw new Error('Nothing submitted.');
1663
+ }
1664
+ let cleansedBody = that.cleanseRequest(req);
1665
+ // Merge
1666
+ for (let prop in cleansedBody) {
1667
+ if (cleansedBody.hasOwnProperty(prop)) {
1668
+ req.doc.set(prop, cleansedBody[prop] === '' ? undefined : cleansedBody[prop]);
1669
+ }
1670
+ }
1671
+ if (req.resource.options.hide !== undefined) {
1672
+ let hiddenFields = that.generateHiddenFields(req.resource, true);
1673
+ hiddenFields._id = false;
1674
+ req.resource.model.findById(req.doc._id, hiddenFields)
1675
+ .lean()
1676
+ .exec()
1677
+ .then((data) => {
1678
+ that.replaceHiddenFields(req.doc, data);
1679
+ that.saveAndRespond(req, res, hiddenFields);
1680
+ })
1681
+ .catch((err) => {
1682
+ throw err; // not sure if this is the right thing to do - didn't have any error-handing here in earlier version
1683
+ });
1684
+ }
1685
+ else {
1686
+ that.saveAndRespond(req, res);
1687
+ }
1688
+ });
1689
+ }, this);
1690
+ }
1691
+ ;
1692
+ generateDependencyList(resource) {
1693
+ if (resource.options.dependents === undefined) {
1694
+ let that = this;
1695
+ resource.options.dependents = that.resources.reduce(function (acc, r) {
1696
+ function searchPaths(schema, prefix) {
1697
+ let fldList = [];
1698
+ for (let fld in schema.paths) {
1699
+ if (schema.paths.hasOwnProperty(fld)) {
1700
+ const parts = fld.split('.');
1701
+ let schemaType = schema.tree;
1702
+ while (parts.length > 0) {
1703
+ schemaType = schemaType[parts.shift()];
1704
+ }
1705
+ if (schemaType.type) {
1706
+ if (schemaType.type.name === 'ObjectId' && schemaType.ref === resource.resourceName) {
1707
+ fldList.push(prefix + fld);
1708
+ }
1709
+ else if (_.isArray(schemaType.type)) {
1710
+ schemaType.type.forEach(function (t) {
1711
+ searchPaths(t, prefix + fld + '.');
1712
+ });
1713
+ }
1714
+ }
1715
+ }
1716
+ }
1717
+ if (fldList.length > 0) {
1718
+ acc.push({ resource: r, keys: fldList });
1719
+ }
1720
+ }
1721
+ searchPaths(r.model.schema, '');
1722
+ return acc;
1723
+ }, []);
1724
+ for (let pluginName in that.options.plugins) {
1725
+ let thisPlugin = that.options.plugins[pluginName];
1726
+ if (thisPlugin.dependencyChecks && thisPlugin.dependencyChecks[resource.resourceName]) {
1727
+ resource.options.dependents = resource.options.dependents.concat(thisPlugin.dependencyChecks[resource.resourceName]);
1728
+ }
1145
1729
  }
1146
- var doc = req.doc;
1147
- if (typeof req.resource.options.onRemove === 'function') {
1148
- req.resource.options.onRemove(doc, req, function (err) {
1149
- if (err) {
1150
- throw err;
1730
+ }
1731
+ }
1732
+ async getDependencies(resource, id) {
1733
+ this.generateDependencyList(resource);
1734
+ let promises = [];
1735
+ let foreignKeyList = [];
1736
+ resource.options.dependents.forEach(collection => {
1737
+ collection.keys.forEach(key => {
1738
+ promises.push({
1739
+ p: collection.resource.model.find({ [key]: id }).limit(1).exec(),
1740
+ collection,
1741
+ key
1742
+ });
1743
+ });
1744
+ });
1745
+ return Promise.all(promises.map(p => p.p))
1746
+ .then((results) => {
1747
+ results.forEach((r, i) => {
1748
+ if (r.length > 0) {
1749
+ foreignKeyList.push({ resourceName: promises[i].collection.resource.resourceName, key: promises[i].key, id: r[0]._id });
1750
+ }
1751
+ });
1752
+ return foreignKeyList;
1753
+ });
1754
+ }
1755
+ entityDelete() {
1756
+ let that = this;
1757
+ return _.bind(async function (req, res, next) {
1758
+ async function removeDoc(doc, resource) {
1759
+ switch (resource.options.handleRemove) {
1760
+ case 'allow':
1761
+ // old behaviour - no attempt to maintain data integrity
1762
+ return doc.deleteOne();
1763
+ case 'cascade':
1764
+ res.status(400).send('"cascade" option not yet supported');
1765
+ break;
1766
+ default:
1767
+ return that.getDependencies(resource, doc._id)
1768
+ .then((dependencies) => {
1769
+ if (dependencies.length > 0) {
1770
+ throw new ForeignKeyError(resource.resourceName, dependencies);
1771
+ }
1772
+ return doc.deleteOne();
1773
+ });
1774
+ }
1775
+ }
1776
+ async function runDeletion(doc, resource) {
1777
+ return new Promise((resolve) => {
1778
+ if (resource.options.onRemove) {
1779
+ resource.options.onRemove(doc, req, async function (err) {
1780
+ if (err) {
1781
+ throw err;
1782
+ }
1783
+ resolve(removeDoc(doc, resource));
1784
+ });
1785
+ }
1786
+ else {
1787
+ resolve(removeDoc(doc, resource));
1151
1788
  }
1152
- internalRemove(doc);
1153
1789
  });
1154
1790
  }
1791
+ this.processEntity(req, res, async function () {
1792
+ if (!req.resource) {
1793
+ next();
1794
+ return;
1795
+ }
1796
+ let doc = req.doc;
1797
+ try {
1798
+ void await runDeletion(doc, req.resource);
1799
+ res.status(200).send();
1800
+ }
1801
+ catch (e) {
1802
+ if (e instanceof ForeignKeyError) {
1803
+ res.status(400).send(e.message);
1804
+ }
1805
+ else {
1806
+ res.status(500).send(e.message);
1807
+ }
1808
+ }
1809
+ });
1810
+ }, this);
1811
+ }
1812
+ ;
1813
+ entityList() {
1814
+ return _.bind(function (req, res, next) {
1815
+ const that = this;
1816
+ this.processEntity(req, res, function () {
1817
+ if (!req.resource) {
1818
+ return next();
1819
+ }
1820
+ const returnRawParam = req.query?.returnRaw ? !!JSON.parse(req.query.returnRaw) : false;
1821
+ if (returnRawParam) {
1822
+ const result = { _id: req.doc._id };
1823
+ for (const field of req.resource.options.listFields) {
1824
+ result[field.field] = req.doc[field.field];
1825
+ }
1826
+ return res.send(result);
1827
+ }
1828
+ else {
1829
+ that.getListFields(req.resource, req.doc, function (err, display) {
1830
+ if (err) {
1831
+ return res.status(500).send(err);
1832
+ }
1833
+ else {
1834
+ return res.send({ list: display });
1835
+ }
1836
+ });
1837
+ }
1838
+ });
1839
+ }, this);
1840
+ }
1841
+ ;
1842
+ // To disambiguate the contents of items - assumed to be the results of a single resource lookup or search -
1843
+ // pass the result of this function as the second argument to the disambiguate() function.
1844
+ // equalityProps should identify the property(s) of the items that must ALL be equal for two items to
1845
+ // be considered ambiguous.
1846
+ // disambiguationResourceName should identify the resource whose list field(s) should be used to generate
1847
+ // the disambiguation text for ambiguous results later.
1848
+ buildSingleResourceAmbiguousRecordStore(items, equalityProps, disambiguationResourceName) {
1849
+ const ambiguousResults = [];
1850
+ for (let i = 0; i < items.length - 1; i++) {
1851
+ for (let j = i + 1; j < items.length; j++) {
1852
+ if (!equalityProps.some((p) => items[i][p] !== items[j][p])) {
1853
+ if (!ambiguousResults.includes(items[i])) {
1854
+ ambiguousResults.push(items[i]);
1855
+ }
1856
+ if (!ambiguousResults.includes(items[j])) {
1857
+ ambiguousResults.push(items[j]);
1858
+ }
1859
+ }
1860
+ }
1861
+ }
1862
+ return { [disambiguationResourceName]: ambiguousResults };
1863
+ }
1864
+ // An alternative to buildSingleResourceAmbiguousRecordStore() for use when disambiguating the results of a
1865
+ // multi-resource lookup or search. In this case, all items need to include the name of the resource that
1866
+ // will be used (when necessary) to yield their disambiguation text later. The property of items that holds
1867
+ // that resource name should be identified by the disambiguationResourceNameProp parameter.
1868
+ // The scary-looking templating used here ensures that the items really do all have an (optional) string
1869
+ // property with the name identified by disambiguationResourceNameProp. For the avoidance of doubt, "prop"
1870
+ // here could be anything - "foo in f" would achieve the same result.
1871
+ buildMultiResourceAmbiguousRecordStore(items, equalityProps, disambiguationResourceNameProp) {
1872
+ const store = {};
1873
+ for (let i = 0; i < items.length - 1; i++) {
1874
+ for (let j = i + 1; j < items.length; j++) {
1875
+ if (items[i][disambiguationResourceNameProp] &&
1876
+ items[i][disambiguationResourceNameProp] === items[j][disambiguationResourceNameProp] &&
1877
+ !equalityProps.some((p) => items[i][p] !== items[j][p])) {
1878
+ if (!store[items[i][disambiguationResourceNameProp]]) {
1879
+ store[items[i][disambiguationResourceNameProp]] = [];
1880
+ }
1881
+ if (!store[items[i][disambiguationResourceNameProp]].includes(items[i])) {
1882
+ store[items[i][disambiguationResourceNameProp]].push(items[i]);
1883
+ }
1884
+ if (!store[items[i][disambiguationResourceNameProp]].includes(items[j])) {
1885
+ store[items[i][disambiguationResourceNameProp]].push(items[j]);
1886
+ }
1887
+ }
1888
+ }
1889
+ }
1890
+ return store;
1891
+ }
1892
+ // return just the id and list fields for all of the records from req.resource.
1893
+ // list fields are those whose schema entry has a value for the "list" attribute (except where this is { ref: true })
1894
+ // if the resource has no explicit list fields identified, the first string field will be returned. if the resource
1895
+ // doesn't have any string fields either, the first (non-id) field will be returned.
1896
+ // usually, we will respond with an array of ILookupItem objects, where the .text property of those objects is the concatenation
1897
+ // of all of the document's list fields (space-seperated).
1898
+ // to request the documents without this transformation applied, include "c=true" in the query string.
1899
+ // the query string can also be used to filter and order the response, by providing values for "f" (find), "l" (limit),
1900
+ // "s" (skip) and/or "o" (order).
1901
+ // results will be disambiguated if req.resource includes disambiguation parameters in its resource options.
1902
+ // where c=true, the disambiguation will be added as a suffix to the .text property of the returned ILookupItem objects.
1903
+ // otherwise, if the resource has just one list field, the disambiguation will be appended to the values of that field, and if
1904
+ // it has multiple list fields, it will be returned as an additional property of the returned (untransformed) objects
1905
+ internalEntityListAll(req, callback) {
1906
+ const projection = this.generateListFieldProjection(req.resource);
1907
+ const listFields = Object.keys(projection);
1908
+ const aggregationParam = req.query.a ? JSON.parse(req.query.a) : null;
1909
+ const findParam = req.query.f ? JSON.parse(req.query.f) : {};
1910
+ const limitParam = req.query.l ? JSON.parse(req.query.l) : 0;
1911
+ const skipParam = req.query.s ? JSON.parse(req.query.s) : 0;
1912
+ const orderParam = req.query.o ? JSON.parse(req.query.o) : req.resource.options.listOrder;
1913
+ const concatenateParam = req.query.c ? JSON.parse(req.query.c) : true;
1914
+ const resOpts = req.resource.options;
1915
+ let disambiguationField;
1916
+ let disambiguationResourceName;
1917
+ if (resOpts?.disambiguation) {
1918
+ disambiguationField = resOpts.disambiguation.field;
1919
+ if (disambiguationField) {
1920
+ projection[disambiguationField] = 1;
1921
+ disambiguationResourceName = resOpts.disambiguation.resource;
1922
+ }
1923
+ }
1924
+ const that = this;
1925
+ this.filteredFind(req.resource, req, aggregationParam, findParam, projection, orderParam, limitParam, skipParam, function (err, docs) {
1926
+ if (err) {
1927
+ return callback(err);
1928
+ }
1155
1929
  else {
1156
- internalRemove(doc);
1930
+ docs = docs.map((d) => d.toObject());
1931
+ if (concatenateParam) {
1932
+ const transformed = docs.map((doc) => {
1933
+ let text = "";
1934
+ for (const field of listFields) {
1935
+ if (doc[field]) {
1936
+ if (text !== "") {
1937
+ text += " ";
1938
+ }
1939
+ text += doc[field];
1940
+ }
1941
+ }
1942
+ const disambiguationId = disambiguationField ? doc[disambiguationField] : undefined;
1943
+ return { id: doc._id, text, disambiguationId };
1944
+ });
1945
+ if (disambiguationResourceName) {
1946
+ that.disambiguate(transformed, that.buildSingleResourceAmbiguousRecordStore(transformed, ["text"], disambiguationResourceName), "disambiguationId", (item, disambiguationText) => {
1947
+ item.text += ` (${disambiguationText})`;
1948
+ }, (err) => {
1949
+ callback(err, transformed);
1950
+ });
1951
+ }
1952
+ else {
1953
+ return callback(null, transformed);
1954
+ }
1955
+ }
1956
+ else {
1957
+ if (disambiguationResourceName) {
1958
+ that.disambiguate(docs, that.buildSingleResourceAmbiguousRecordStore(docs, listFields, disambiguationResourceName), disambiguationField, (item, disambiguationText) => {
1959
+ if (listFields.length === 1) {
1960
+ item[listFields[0]] += ` (${disambiguationText})`;
1961
+ }
1962
+ else {
1963
+ // store the text against hard-coded property name "disambiguation", rather than (say) using
1964
+ // item[disambiguationResourceName], because if disambiguationResourceName === disambiguationField,
1965
+ // that value would end up being deleted again when the this.disambiguate() call (which we have
1966
+ // been called from) does its final tidy-up and deletes [disambiguationField] from all of the items in docs
1967
+ item.disambiguation = disambiguationText;
1968
+ }
1969
+ }, (err) => {
1970
+ callback(err, docs);
1971
+ });
1972
+ }
1973
+ else {
1974
+ return callback(null, docs);
1975
+ }
1976
+ }
1157
1977
  }
1158
1978
  });
1159
- }, this);
1160
- };
1161
- DataForm.prototype.entityList = function () {
1162
- return _.bind(function (req, res, next) {
1163
- var that = this;
1164
- this.processEntity(req, res, function () {
1165
- if (!req.resource) {
1979
+ }
1980
+ ;
1981
+ entityListAll() {
1982
+ return _.bind(function (req, res, next) {
1983
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
1166
1984
  return next();
1167
1985
  }
1168
- that.getListFields(req.resource, req.doc, function (err, display) {
1986
+ this.internalEntityListAll(req, function (err, resultsObject) {
1169
1987
  if (err) {
1170
- return res.status(500).send(err);
1988
+ res.status(400, err);
1171
1989
  }
1172
1990
  else {
1173
- return res.send({ list: display });
1991
+ res.send(resultsObject);
1174
1992
  }
1175
1993
  });
1176
- });
1177
- }, this);
1178
- };
1994
+ }, this);
1995
+ }
1996
+ ;
1997
+ extractTimestampFromMongoID(record) {
1998
+ let timestamp = record.toString().substring(0, 8);
1999
+ return new Date(parseInt(timestamp, 16) * 1000);
2000
+ }
2001
+ }
2002
+ exports.FormsAngular = FormsAngular;
2003
+ class ForeignKeyError extends global.Error {
2004
+ constructor(resourceName, foreignKeys) {
2005
+ super(`Cannot delete this ${resourceName}, as it is: ${foreignKeys.map(d => ` the ${d.key} on ${d.resourceName} ${d.id}`).join("; ")}`);
2006
+ this.name = "ForeignKeyError";
2007
+ this.stack = new global.Error('').stack;
2008
+ }
2009
+ }