forms-angular 0.12.0-beta.36 → 0.12.0-beta.361

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