forms-angular 0.12.0-beta.28 → 0.12.0-beta.280

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