forms-angular 0.12.0-beta.35 → 0.12.0-beta.351

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,558 @@ 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
+ resultObject.matched = resultObject.matched || [];
555
+ if (item.combined) {
556
+ if (multiMatchPossible) {
557
+ resultObject.matched = searchStrings.map((word, i) => i);
558
+ }
559
+ else {
560
+ resultObject.exact = true;
561
+ }
253
562
  }
254
- for (var m = 0; m < indexedFields.length; m++) {
255
- searches.push({ resource: resource, field: indexedFields[m] });
563
+ else {
564
+ const fieldValue = typeof aDoc[item.field] === "string" ? aDoc[item.field].toLowerCase() : undefined;
565
+ if (fieldValue !== undefined) {
566
+ if (multiMatchPossible) {
567
+ // record the index of string that matched, so we don't count it against another field
568
+ // where more than one word matches (searching for "su sue" and finding "Susan") take the longest
569
+ let i = -1;
570
+ searchStrings.forEach((word, idx) => {
571
+ if (!resultObject.matched.includes(idx) &&
572
+ fieldValue.indexOf(word) === 0 &&
573
+ (i === -1 || word.length > searchStrings[i].length)) {
574
+ i = idx;
575
+ }
576
+ });
577
+ if (i > -1) {
578
+ resultObject.matched.push(i);
579
+ }
580
+ if (fieldValue.indexOf(searchFor) === 0) {
581
+ // A field starting with the whole phrase covers every word, so ranks the same as matching every word
582
+ // across separate fields ("Tony Bates" and "Bates, Tony" both match "tony bates" equally)
583
+ resultObject.matched = searchStrings.map((word, i) => i);
584
+ }
585
+ }
586
+ else if (fieldValue === searchFor) {
587
+ resultObject.exact = true;
588
+ }
589
+ }
256
590
  }
591
+ resultObject.addHits = calcAddHits(resultObject);
592
+ return resultObject.addHits < before || matchedChars(resultObject) > charsBefore;
257
593
  }
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;
594
+ let handleSearchResultsFromIndex = function (err, docs, item, cb) {
595
+ function handleSingleSearchResult(aDoc, cbdoc) {
596
+ let thisId = aDoc._id.toString(), resultObject, resultPos;
268
597
  function handleResultsInList() {
269
- resultObject.searchImportance = item.resource.options.searchImportance || 99;
598
+ recordMatches(resultObject, aDoc, item);
599
+ resultObject.resourceCollection = item.resource.resourceName;
600
+ resultObject.searchImportance =
601
+ item.resource.options.searchImportance || 99;
270
602
  if (item.resource.options.localisationData) {
271
603
  resultObject.resource = translate(resultObject.resource, item.resource.options.localisationData, "resource");
272
604
  resultObject.resourceText = translate(resultObject.resourceText, item.resource.options.localisationData, "resourceText");
@@ -275,32 +607,42 @@ DataForm.prototype.internalSearch = function (req, resourcesToSearch, includeRes
275
607
  results.splice(_.sortedIndexBy(results, resultObject, calcResultValue), 0, resultObject);
276
608
  cbdoc(null);
277
609
  }
610
+ // Do we already have them in the list?
278
611
  for (resultPos = results.length - 1; resultPos >= 0; resultPos--) {
279
- if (results[resultPos].id.toString() === thisId) {
612
+ // check for matching id and resource
613
+ if (results[resultPos].id.toString() === thisId && results[resultPos].resourceCollection === item.resource.resourceName) {
280
614
  break;
281
615
  }
282
616
  }
283
617
  if (resultPos >= 0) {
284
- resultObject = {};
285
- extend(resultObject, results[resultPos]);
618
+ resultObject = Object.assign({}, results[resultPos]);
619
+ resultObject.matched = [...(resultObject.matched || [])];
286
620
  // 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);
621
+ if (recordMatches(resultObject, aDoc, item)) {
622
+ // remove it from current position
623
+ results.splice(resultPos, 1);
624
+ // and re-insert where appropriate
625
+ results.splice(_.sortedIndexBy(results, resultObject, calcResultValue), 0, resultObject);
290
626
  }
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
627
  cbdoc(null);
296
628
  }
297
629
  else {
298
630
  // Otherwise add them new...
631
+ let disambiguationId;
632
+ const opts = item.resource.options;
633
+ const disambiguationResource = opts.disambiguation?.resource;
634
+ if (disambiguationResource) {
635
+ disambiguationId = aDoc[opts.disambiguation.field]?.toString();
636
+ }
299
637
  // Use special listings format if defined
300
- var specialListingFormat = item.resource.options.searchResultFormat;
638
+ let specialListingFormat = item.resource.options.searchResultFormat;
301
639
  if (specialListingFormat) {
302
- resultObject = specialListingFormat.apply(aDoc);
303
- handleResultsInList();
640
+ specialListingFormat.apply(aDoc, [req]).then((resultObj) => {
641
+ resultObject = resultObj;
642
+ resultObject.disambiguationResource = disambiguationResource;
643
+ resultObject.disambiguationId = disambiguationId;
644
+ handleResultsInList();
645
+ });
304
646
  }
305
647
  else {
306
648
  that.getListFields(item.resource, aDoc, function (err, description) {
@@ -311,430 +653,796 @@ DataForm.prototype.internalSearch = function (req, resourcesToSearch, includeRes
311
653
  resultObject = {
312
654
  id: aDoc._id,
313
655
  weighting: 9999,
314
- text: description
656
+ disambiguationResource,
657
+ disambiguationId,
658
+ text: description,
315
659
  };
316
660
  if (resourceCount > 1 || includeResourceInResults) {
317
- resultObject.resource = resultObject.resourceText = item.resource.resourceName;
661
+ resultObject.resource = resultObject.resourceText =
662
+ item.resource.resourceName;
318
663
  }
319
664
  handleResultsInList();
320
665
  }
321
666
  });
322
667
  }
323
668
  }
324
- }, function (err) {
669
+ }
670
+ if (!err && docs && docs.length > 0) {
671
+ async.map(docs, handleSingleSearchResult, cb);
672
+ }
673
+ else {
325
674
  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];
675
+ }
676
+ };
677
+ this.searchFunc(searches, function (item, cb) {
678
+ let searchDoc = {};
679
+ let searchFilter = filter || item.filter;
680
+ if (item.combined) {
681
+ if (!combinedCriteria) {
682
+ // wildcard search - the per-field searches will find everything
683
+ return cb();
684
+ }
685
+ if (searchFilter) {
686
+ that.hackVariables(searchFilter);
687
+ extend(searchDoc, searchFilter);
688
+ }
689
+ searchDoc["$and"] = [
690
+ ...(searchDoc["$and"] || []),
691
+ combinedCriteria(item.resource.options.searchFields),
692
+ ];
693
+ }
694
+ else if (searchFilter) {
695
+ that.hackVariables(searchFilter);
696
+ extend(searchDoc, searchFilter);
697
+ if (searchFilter[item.field]) {
698
+ delete searchDoc[item.field];
699
+ let obj1 = {}, obj2 = {};
700
+ obj1[item.field] = searchFilter[item.field];
701
+ obj2[item.field] = searchCriteria;
702
+ searchDoc["$and"] = [obj1, obj2];
703
+ }
704
+ else {
705
+ if (searchCriteria) {
706
+ searchDoc[item.field] = searchCriteria;
707
+ }
708
+ }
343
709
  }
344
710
  else {
345
- searchDoc[item.field] = searchCriteria;
711
+ if (searchCriteria) {
712
+ searchDoc[item.field] = searchCriteria;
713
+ }
346
714
  }
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);
715
+ /*
716
+ 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.
717
+ 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
718
+ 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
719
+ results end up containing people who only match either c or e (but have been accessed much more recently).
720
+
721
+ Increasing the number would be a short term fix at the cost of slowing down the search.
722
+ */
723
+ // TODO : Figure out a better way to deal with this
724
+ if (item.resource.options.searchFunc) {
725
+ item.resource.options.searchFunc(item.resource, req, null, searchDoc, item.resource.options.searchOrder, limit ? limit + 200 : 0, null, function (err, docs) {
726
+ handleSearchResultsFromIndex(err, docs, item, cb);
727
+ });
377
728
  }
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 = {};
729
+ else {
730
+ that.filteredFind(item.resource, req, null, searchDoc, null, item.resource.options.searchOrder, limit ? limit + 200 : 0, null, function (err, docs) {
731
+ handleSearchResultsFromIndex(err, docs, item, cb);
732
+ });
733
+ }
734
+ }, function (err) {
735
+ if (err) {
736
+ callback(err);
737
+ }
738
+ else {
739
+ // Strip weighting and match details from the results
740
+ results = _.map(results, function (aResult) {
741
+ delete aResult.weighting;
742
+ delete aResult.exact;
743
+ return aResult;
744
+ });
745
+ if (limit && results.length > limit) {
746
+ moreCount += results.length - limit;
747
+ results.splice(limit);
748
+ }
749
+ that.disambiguate(results, that.buildMultiResourceAmbiguousRecordStore(results, ["text"], "disambiguationResource"), "disambiguationId", (item, disambiguationText) => {
750
+ item.text += ` (${disambiguationText})`;
751
+ }, (err) => {
752
+ if (err) {
753
+ callback(err);
754
+ }
755
+ else {
756
+ // the disambiguate() call will have deleted the disambiguationIds but we're responsible for
757
+ // the disambiguationResources, which we shouldn't be returning to the client
758
+ for (const result of results) {
759
+ delete result.disambiguationResource;
442
760
  }
443
- outPath[fld].options.form[override] = schema[fld][override];
761
+ timestamps.completedAt = new Date().valueOf();
762
+ callback(null, { results, moreCount, timestamps });
444
763
  }
445
- }
764
+ });
446
765
  }
447
- }
766
+ });
767
+ }
768
+ wrapInternalSearch(req, res, resourcesToSearch, includeResourceInResults, limit) {
769
+ this.internalSearch(req, resourcesToSearch, includeResourceInResults, limit, function (err, resultsObject) {
770
+ if (err) {
771
+ res.status(400, err);
772
+ }
773
+ else {
774
+ res.send(resultsObject);
775
+ }
776
+ });
448
777
  }
449
- else {
450
- outPath = vanilla;
778
+ search() {
779
+ return _.bind(function (req, res, next) {
780
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
781
+ return next();
782
+ }
783
+ this.wrapInternalSearch(req, res, [req.resource], false, 0);
784
+ }, this);
451
785
  }
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;
786
+ searchAll() {
787
+ return _.bind(function (req, res) {
788
+ this.wrapInternalSearch(req, res, this.resources, true, 10);
789
+ }, this);
459
790
  }
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
- }
791
+ models() {
792
+ const that = this;
793
+ return function (req, res) {
794
+ // Check for optional modelFilter and call it with the request and current list. Otherwise just return the list.
795
+ let resources = that.options.modelFilter
796
+ ? that.options.modelFilter.call(null, req, that.resources)
797
+ : that.resources;
798
+ if (req.query?.resourceNamesOnly) {
799
+ resources = resources.map((r) => r.resourceName);
469
800
  }
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';
801
+ res.send(resources);
802
+ };
803
+ }
804
+ renderError(err, redirectUrl, req, res) {
805
+ res.statusMessage = err?.message || err;
806
+ res.status(400).end(err?.message || err);
807
+ }
808
+ redirect(address, req, res) {
809
+ res.send(address);
810
+ }
811
+ applySchemaSubset(vanilla, schema) {
812
+ let outPath;
813
+ if (schema) {
814
+ outPath = {};
815
+ for (let fld in schema) {
816
+ if (schema.hasOwnProperty(fld)) {
817
+ if (vanilla[fld]) {
818
+ outPath[fld] = _.cloneDeep(vanilla[fld]);
819
+ if (vanilla[fld].schema) {
820
+ outPath[fld].schema = this.applySchemaSubset(outPath[fld].schema, schema[fld].schema);
821
+ }
822
+ }
823
+ else {
824
+ if (fld.slice(0, 8) === "_bespoke") {
825
+ outPath[fld] = {
826
+ path: fld,
827
+ instance: schema[fld]._type,
828
+ };
478
829
  }
479
830
  else {
480
- realType.instance = typeType;
831
+ throw new Error("No such field as " +
832
+ fld +
833
+ ". Is it part of a sub-doc? If so you need the bit before the period.");
481
834
  }
482
835
  }
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;
836
+ outPath[fld].options = outPath[fld].options || {};
837
+ for (const override in schema[fld]) {
838
+ if (schema[fld].hasOwnProperty(override)) {
839
+ if (override.slice(0, 1) !== "_") {
840
+ if (schema[fld].hasOwnProperty(override)) {
841
+ if (!outPath[fld].options.form) {
842
+ outPath[fld].options.form = {};
843
+ }
844
+ outPath[fld].options.form[override] = schema[fld][override];
845
+ }
846
+ }
847
+ }
496
848
  }
497
- listFields.push(listFieldInfo);
498
849
  }
499
850
  }
500
851
  }
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 = {};
852
+ else {
853
+ outPath = vanilla;
533
854
  }
534
- var reportSchema;
535
- if (req.params.reportName) {
536
- reportSchema = req.resource.model.schema.statics['report'](req.params.reportName, req);
855
+ return outPath;
856
+ }
857
+ preprocess(resource, paths, formName, formSchema) {
858
+ function processInternalObject(obj) {
859
+ return Object.keys(obj).reduce((acc, cur) => {
860
+ const curType = typeof obj[cur];
861
+ if ((!["$", "_"].includes(cur.charAt(0)) ||
862
+ [
863
+ "$in",
864
+ "$nin",
865
+ "$eq",
866
+ "$ne",
867
+ "$gt",
868
+ "$gte",
869
+ "$lt",
870
+ "$lte",
871
+ "$regex",
872
+ "$or",
873
+ "$exists",
874
+ ].includes(cur)) &&
875
+ curType !== "function") {
876
+ const val = obj[cur];
877
+ if (val) {
878
+ if (Array.isArray(val)) {
879
+ if (val.length > 0) {
880
+ acc[cur] = val;
881
+ }
882
+ }
883
+ else if (curType === "object" &&
884
+ !(val instanceof Date) &&
885
+ !(val instanceof RegExp)) {
886
+ acc[cur] = processInternalObject(obj[cur]);
887
+ }
888
+ else {
889
+ acc[cur] = obj[cur];
890
+ }
891
+ }
892
+ }
893
+ return acc;
894
+ }, {});
537
895
  }
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
- }
896
+ let outPath = {}, hiddenFields = [], listFields = [];
897
+ if (resource &&
898
+ !resource.options?.doNotCacheSchema &&
899
+ resource.preprocessed &&
900
+ resource.preprocessed[formName || "__default"]) {
901
+ return resource.preprocessed[formName || "__default"].paths;
549
902
  }
550
903
  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;
904
+ if (resource && resource.options && resource.options.idIsList) {
905
+ paths["_id"].options = paths["_id"].options || {};
906
+ paths["_id"].options.list = resource.options.idIsList;
907
+ }
908
+ for (let element in paths) {
909
+ if (paths.hasOwnProperty(element) && element !== "__v") {
910
+ // check for schemas
911
+ if (paths[element].schema) {
912
+ let subSchemaInfo = this.preprocess(null, paths[element].schema.paths);
913
+ outPath[element] = { schema: subSchemaInfo.paths };
914
+ if (paths[element].options.form) {
915
+ outPath[element].options = {
916
+ form: extend(true, {}, paths[element].options.form),
917
+ };
918
+ }
919
+ // this provides support for entire nested schemas that wish to remain hidden
920
+ if (paths[element].options.secure) {
921
+ hiddenFields.push(element);
922
+ }
923
+ // to support hiding individual properties of nested schema would require us
924
+ // to do something with subSchemaInfo.hide here
925
+ }
926
+ else {
927
+ // check for arrays
928
+ let realType = paths[element].caster
929
+ ? paths[element].caster
930
+ : paths[element];
931
+ if (!realType.instance) {
932
+ if (realType.options.type) {
933
+ let type = realType.options.type(), typeType = typeof type;
934
+ if (typeType === "string") {
935
+ realType.instance = !isNaN(Date.parse(type))
936
+ ? "Date"
937
+ : "String";
938
+ }
939
+ else {
940
+ realType.instance = typeType;
941
+ }
942
+ }
943
+ }
944
+ outPath[element] = processInternalObject(paths[element]);
945
+ if (paths[element].options.secure) {
946
+ hiddenFields.push(element);
947
+ }
948
+ if (paths[element].options.match) {
949
+ outPath[element].options.match =
950
+ paths[element].options.match.source ||
951
+ paths[element].options.match;
952
+ }
953
+ let schemaListInfo = paths[element].options.list;
954
+ if (schemaListInfo) {
955
+ let listFieldInfo = { field: element };
956
+ if (typeof schemaListInfo === "object" &&
957
+ Object.keys(schemaListInfo).length > 0) {
958
+ listFieldInfo.params = schemaListInfo;
959
+ }
960
+ listFields.push(listFieldInfo);
557
961
  }
558
962
  }
559
963
  }
560
964
  }
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);
965
+ outPath = this.applySchemaSubset(outPath, formSchema);
966
+ let returnObj = { paths: outPath };
967
+ if (hiddenFields.length > 0) {
968
+ returnObj.hide = hiddenFields;
574
969
  }
575
- else {
576
- res.send(result);
970
+ if (listFields.length > 0) {
971
+ returnObj.listFields = listFields;
577
972
  }
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']);
973
+ if (resource && !resource.options?.doNotCacheSchema) {
974
+ resource.preprocessed = resource.preprocessed || {};
975
+ resource.preprocessed[formName || "__default"] = returnObj;
976
+ }
977
+ return returnObj;
585
978
  }
586
979
  }
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');
980
+ schema() {
981
+ return _.bind(function (req, res) {
982
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
983
+ return res.status(404).end();
984
+ }
985
+ let formSchema = null;
986
+ const formName = req.params.formName;
987
+ if (req.resource.preprocessed?.[formName || "__default"]) {
988
+ res.send(req.resource.preprocessed[formName || "__default"].paths);
989
+ }
990
+ else {
991
+ if (formName) {
992
+ try {
993
+ formSchema = req.resource.model.schema.statics["form"](escapeHtml(formName), req);
994
+ }
995
+ catch (e) {
996
+ return res.status(404).send(e.message);
997
+ }
599
998
  }
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]);
999
+ let paths = this.preprocess(req.resource, req.resource.model.schema.paths, formName, formSchema).paths;
1000
+ res.send(paths);
1001
+ }
1002
+ }, this);
1003
+ }
1004
+ report() {
1005
+ return _.bind(async function (req, res, next) {
1006
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
1007
+ return next();
1008
+ }
1009
+ const self = this;
1010
+ req._isReport = true; // Can be used to modify findFunc behaviour
1011
+ if (typeof req.query === "undefined") {
1012
+ req.query = {};
1013
+ }
1014
+ let reportSchema;
1015
+ if (req.params.reportName) {
1016
+ try {
1017
+ reportSchema = await req.resource.model.schema.statics["report"](req.params.reportName, req);
1018
+ }
1019
+ catch (e) {
1020
+ res.send({ success: false, error: e.message || e });
1021
+ }
1022
+ }
1023
+ else if (req.query.r) {
1024
+ switch (req.query.r[0]) {
1025
+ case "[":
1026
+ reportSchema = { pipeline: JSON.parse(req.query.r) };
1027
+ break;
1028
+ case "{":
1029
+ reportSchema = JSON.parse(req.query.r);
1030
+ break;
1031
+ default:
1032
+ return self.renderError(new Error('Invalid "r" parameter'), null, req, res);
1033
+ }
1034
+ }
1035
+ else {
1036
+ let fields = {};
1037
+ for (let key in req.resource.model.schema.paths) {
1038
+ if (req.resource.model.schema.paths.hasOwnProperty(key)) {
1039
+ if (key !== "__v" &&
1040
+ !req.resource.model.schema.paths[key].options.secure) {
1041
+ if (key.indexOf(".") === -1) {
1042
+ fields[key] = 1;
1043
+ }
1044
+ }
604
1045
  }
605
1046
  }
1047
+ reportSchema = {
1048
+ pipeline: [{ $project: fields }],
1049
+ drilldown: req.params.resourceName + "/|_id|/edit",
1050
+ };
606
1051
  }
607
- else if (_.isObject(obj[prop])) {
608
- this.hackVariables(obj[prop]);
1052
+ // Replace parameters in pipeline
1053
+ let schemaCopy = {};
1054
+ extend(schemaCopy, reportSchema);
1055
+ schemaCopy.params = schemaCopy.params || [];
1056
+ self.reportInternal(req, req.resource, schemaCopy, function (err, result) {
1057
+ if (err) {
1058
+ res.send({ success: false, error: err.message || err });
1059
+ }
1060
+ else {
1061
+ res.send(result);
1062
+ }
1063
+ });
1064
+ }, this);
1065
+ }
1066
+ hackVariablesInPipeline(runPipeline) {
1067
+ for (let pipelineSection = 0; pipelineSection < runPipeline.length; pipelineSection++) {
1068
+ let sectionType = Object.keys(runPipeline[pipelineSection])[0];
1069
+ if (["$match", "$group", "$project"].includes(sectionType)) {
1070
+ this.hackVariables(runPipeline[pipelineSection][sectionType]);
609
1071
  }
610
1072
  }
611
1073
  }
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 = {};
1074
+ hackVariables(obj) {
1075
+ // Replace variables that cannot be serialised / deserialised. Bit of a hack, but needs must...
1076
+ // Anything formatted 1800-01-01T00:00:00.000Z or 1800-01-01T00:00:00.000+0000 is converted to a Date
1077
+ // Only handles the cases I need for now
1078
+ // TODO: handle arrays etc
1079
+ for (const prop in obj) {
1080
+ if (obj.hasOwnProperty(prop)) {
1081
+ if (typeof obj[prop] === "string") {
1082
+ 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]);
1083
+ if (dateTest) {
1084
+ obj[prop] = new Date(dateTest[1] + "Z");
1085
+ }
1086
+ else if (prop !== "$regex") {
1087
+ const objectIdTest = /^([0-9a-fA-F]{24})$/.exec(obj[prop]);
1088
+ if (objectIdTest) {
1089
+ obj[prop] = new Types.ObjectId(objectIdTest[1]);
1090
+ }
1091
+ }
1092
+ }
1093
+ else if (_.isObject(obj[prop])) {
1094
+ this.hackVariables(obj[prop]);
1095
+ }
1096
+ }
1097
+ }
619
1098
  }
620
- self.doFindFunc(req, resource, function (err, queryObj) {
621
- if (err) {
622
- return 'There was a problem with the findFunc for model';
1099
+ rejectForbiddenPipelineOperators(obj) {
1100
+ if (Array.isArray(obj)) {
1101
+ obj.forEach((elm) => this.rejectForbiddenPipelineOperators(elm));
623
1102
  }
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
- }
1103
+ else if (obj && typeof obj === "object" && !(obj instanceof Types.ObjectId) && !(obj instanceof Date)) {
1104
+ for (const key of Object.keys(obj)) {
1105
+ if (FormsAngular.forbiddenPipelineOperators.includes(key)) {
1106
+ throw new Error(`Unsupported pipeline operator ${key}`);
1107
+ }
1108
+ this.rejectForbiddenPipelineOperators(obj[key]);
1109
+ }
1110
+ }
1111
+ }
1112
+ async sanitisePipeline(aggregationParam, hiddenFields, findFuncQry, req) {
1113
+ let that = this;
1114
+ let array = Array.isArray(aggregationParam)
1115
+ ? aggregationParam
1116
+ : [aggregationParam];
1117
+ this.rejectForbiddenPipelineOperators(array);
1118
+ let retVal = [];
1119
+ let doneHiddenFields = false;
1120
+ const haveHiddenFields = hiddenFields && Object.keys(hiddenFields).length > 0;
1121
+ if (findFuncQry) {
1122
+ retVal.unshift({ $match: findFuncQry });
1123
+ }
1124
+ // Sanitise a pipeline that runs against a joined collection, restricting it with that collection's own findFunc
1125
+ // and removing that collection's hidden fields. Collections that are not resources are assumed to hold nothing
1126
+ // sensitive, so are not restricted.
1127
+ async function sanitiseJoinedPipeline(pipeline, resource) {
1128
+ let joinedHiddenFields = {};
1129
+ let joinedFindFuncQry;
1130
+ if (resource) {
1131
+ if (resource.options?.hide?.length > 0) {
1132
+ joinedHiddenFields = that.generateHiddenFields(resource, false);
631
1133
  }
1134
+ joinedFindFuncQry = await that.doFindFuncPromise(req, resource);
1135
+ }
1136
+ return that.sanitisePipeline(pipeline || [], joinedHiddenFields, joinedFindFuncQry, req);
1137
+ }
1138
+ for (let pipelineSection = 0; pipelineSection < array.length; pipelineSection++) {
1139
+ let stage = array[pipelineSection];
1140
+ let keys = Object.keys(stage);
1141
+ if (keys.length !== 1) {
1142
+ throw new Error("Invalid pipeline instruction");
632
1143
  }
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;
1144
+ if (!doneHiddenFields && keys[0] !== "$match") {
1145
+ // Leading $match stages may select on hidden fields, but nothing after them can see those fields
1146
+ if (haveHiddenFields) {
1147
+ retVal.push({ $project: hiddenFields });
1148
+ }
1149
+ doneHiddenFields = true;
1150
+ }
1151
+ switch (keys[0]) {
1152
+ case "$project":
1153
+ case "$addFields":
1154
+ case "$count":
1155
+ case "$group":
1156
+ case "$unset":
1157
+ case "$limit":
1158
+ case "$replaceRoot":
1159
+ case "$replaceWith":
1160
+ case "$sort":
1161
+ case "$unwind":
1162
+ // We don't care about these - they are all (as far as we know) safe
1163
+ break;
1164
+ case "$facet":
1165
+ // Each facet is a pipeline in its own right, running against the documents that reach this stage (which
1166
+ // have already been through our findFunc and had hidden fields removed), but it can join other collections
1167
+ for (const facetName of Object.keys(stage.$facet)) {
1168
+ stage.$facet[facetName] = await that.sanitisePipeline(stage.$facet[facetName], {}, undefined, req);
639
1169
  }
640
- else if (_.isObject(sparam.value)) {
641
- return JSON.stringify(sparam.value);
1170
+ break;
1171
+ case "$unionWith":
1172
+ if (!stage.$unionWith.coll) {
1173
+ stage.$unionWith = { coll: stage.$unionWith, pipeline: [] };
642
1174
  }
643
- else if (sparam.value[0] === '{') {
644
- return sparam.value;
1175
+ stage.$unionWith.pipeline = await sanitiseJoinedPipeline(stage.$unionWith.pipeline, that.getResourceFromCollection(stage.$unionWith.coll));
1176
+ break;
1177
+ case "$match":
1178
+ this.hackVariables(array[pipelineSection]["$match"]);
1179
+ break;
1180
+ case "$lookup":
1181
+ case "$graphLookup":
1182
+ let needFindFunc = true;
1183
+ const collectionName = stage[keys[0]].from;
1184
+ const lookupField = stage[keys[0]].as;
1185
+ if (typeof collectionName !== "string" || typeof lookupField !== "string" || (collectionName + lookupField).indexOf("$") !== -1) {
1186
+ throw new Error('No support for lookups where the "from" or "as" is anything other than a simple string');
645
1187
  }
646
- else {
647
- return '"' + sparam.value + '"';
1188
+ const resource = that.getResourceFromCollection(collectionName);
1189
+ if (keys[0] === "$lookup") {
1190
+ let lookupProps = Object.keys(stage.$lookup);
1191
+ // First deal with simple $lookups with a single join field equality
1192
+ if ((lookupProps.length === 4 || lookupProps.length === 5) &&
1193
+ lookupProps.includes("from") &&
1194
+ lookupProps.includes("localField") &&
1195
+ lookupProps.includes("foreignField") &&
1196
+ lookupProps.includes("as")) {
1197
+ if (lookupProps.length === 4) {
1198
+ // nothing to do
1199
+ }
1200
+ else if (lookupProps.length === 5 && lookupProps.includes("pipeline")) {
1201
+ stage.$lookup.pipeline = await sanitiseJoinedPipeline(stage.$lookup.pipeline, resource);
1202
+ }
1203
+ else {
1204
+ throw new Error("Unsupported $lookup format");
1205
+ }
1206
+ }
1207
+ else if (lookupProps.length === 4 &&
1208
+ lookupProps.includes("from") &&
1209
+ lookupProps.includes("let") &&
1210
+ lookupProps.includes("pipeline") &&
1211
+ lookupProps.includes("as")) {
1212
+ stage.$lookup.pipeline = await sanitiseJoinedPipeline(stage.$lookup.pipeline, resource);
1213
+ }
1214
+ else {
1215
+ throw new Error(`No support for $lookup of with properties ${lookupProps.join(', ')}`);
1216
+ }
648
1217
  }
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 * ';
1218
+ if (resource) {
1219
+ retVal.push(stage);
1220
+ stage = null;
1221
+ if (resource.options?.hide?.length > 0) {
1222
+ const hiddenLookupFields = this.generateHiddenFields(resource, false);
1223
+ let hiddenFieldsObj = {};
1224
+ Object.keys(hiddenLookupFields).forEach((hf) => {
1225
+ hiddenFieldsObj[`${lookupField}.${hf}`] = false;
686
1226
  });
1227
+ retVal.push({ $project: hiddenFieldsObj });
687
1228
  }
688
- schema.columnTranslations.forEach(function (columnTranslation) {
689
- if (columnTranslation.translations) {
690
- doATranslate(columnTranslation, columnTranslation);
1229
+ // Now we need to make sure that we restrict the lookup to documents we have access to (or can provide the _id of)
1230
+ if (needFindFunc && resource.options.findFunc) {
1231
+ let allowNulls = false;
1232
+ // If the next stage is an $unwind
1233
+ let nextStageIsUnwind = false;
1234
+ const nextStage = array[pipelineSection + 1];
1235
+ if (nextStage) {
1236
+ let nextKeys = Object.keys(nextStage);
1237
+ if (nextKeys.length !== 1) {
1238
+ throw new Error("Invalid pipeline instruction");
1239
+ }
1240
+ if (nextKeys[0] === "$unwind") {
1241
+ if (nextStage["$unwind"] === "$" + lookupField) {
1242
+ nextStageIsUnwind = true;
1243
+ }
1244
+ if (nextStage["$unwind"] &&
1245
+ nextStage["$unwind"].path === "$" + lookupField) {
1246
+ nextStageIsUnwind = true;
1247
+ if (nextStage["$unwind"].preserveNullAndEmptyArrays) {
1248
+ allowNulls = true;
1249
+ }
1250
+ }
1251
+ }
691
1252
  }
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);
1253
+ if (!nextStageIsUnwind) {
1254
+ throw new Error("No support for $lookup where the next stage is not an $unwind and the resources has a findFunc");
1255
+ }
1256
+ // Push the $unwind, add our own findFunc, and increment the pipelineStage counter
1257
+ retVal.push(array[pipelineSection + 1]);
1258
+ let lookedUpFindQry = await this.doFindFuncPromise(req, resource);
1259
+ if (lookedUpFindQry) {
1260
+ // Now we need to put the lookup base into the criteria
1261
+ for (const prop in lookedUpFindQry) {
1262
+ if (lookedUpFindQry.hasOwnProperty(prop)) {
1263
+ lookedUpFindQry[`${lookupField}.${prop}`] =
1264
+ lookedUpFindQry[prop];
1265
+ delete lookedUpFindQry[prop];
1266
+ }
1267
+ }
1268
+ if (allowNulls) {
1269
+ lookedUpFindQry = {
1270
+ $or: [
1271
+ lookedUpFindQry,
1272
+ { [lookupField]: { $exists: false } },
1273
+ ],
1274
+ };
1275
+ }
1276
+ retVal.push({ $match: lookedUpFindQry });
1277
+ }
1278
+ pipelineSection++;
1279
+ }
1280
+ }
1281
+ break;
1282
+ default:
1283
+ // anything else is either known to be dangerous, not yet needed or we don't know what it is
1284
+ throw new Error("Unsupported pipeline instruction " + keys[0]);
1285
+ }
1286
+ if (stage) {
1287
+ retVal.push(stage);
1288
+ }
1289
+ }
1290
+ if (!doneHiddenFields && haveHiddenFields) {
1291
+ // The pipeline was nothing but $match stages
1292
+ retVal.push({ $project: hiddenFields });
1293
+ }
1294
+ return retVal;
1295
+ }
1296
+ reportInternal(req, resource, schema, callback) {
1297
+ let runPipelineStr;
1298
+ let runPipelineObj;
1299
+ let self = this;
1300
+ if (typeof req.query === "undefined") {
1301
+ req.query = {};
1302
+ }
1303
+ self.doFindFunc(req, resource, function (err, queryObj) {
1304
+ if (err) {
1305
+ return "There was a problem with the findFunc for model";
1306
+ }
1307
+ else {
1308
+ runPipelineStr = JSON.stringify(schema.pipeline);
1309
+ for (let param in req.query) {
1310
+ if (param !== "noinput" && req.query.hasOwnProperty(param)) {
1311
+ if (req.query[param]) {
1312
+ if (param !== "r") {
1313
+ // we don't want to copy the whole report schema (again!)
1314
+ if (schema.params[param] !== undefined) {
1315
+ schema.params[param].value = req.query[param];
698
1316
  }
699
1317
  else {
700
- cb('Invalid ref property of ' + columnTranslation.ref + ' in columnTranslations ' + columnTranslation.field);
1318
+ return callback(`No such parameter as ${param} - try one of ${Object.keys(schema.params).join()}`);
701
1319
  }
702
1320
  }
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
1321
  }
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;
1322
+ }
1323
+ }
1324
+ // Replace parameters with the value
1325
+ if (runPipelineStr) {
1326
+ runPipelineStr = runPipelineStr.replace(/"\(.+?\)"/g, function (match) {
1327
+ let sparam = schema.params[match.slice(2, -2)];
1328
+ if (sparam !== undefined) {
1329
+ if (sparam.type === "number") {
1330
+ return sparam.value;
1331
+ }
1332
+ else if (_.isObject(sparam.value)) {
1333
+ return JSON.stringify(sparam.value);
1334
+ }
1335
+ else if (sparam.value[0] === "{") {
1336
+ return sparam.value;
1337
+ }
1338
+ else {
1339
+ return '"' + sparam.value + '"';
1340
+ }
1341
+ }
1342
+ else {
1343
+ return callback(`No such parameter as ${match.slice(2, -2)} - try one of ${Object.keys(schema.params).join()}`);
1344
+ }
1345
+ });
1346
+ }
1347
+ runPipelineObj = JSON.parse(runPipelineStr);
1348
+ self.hackVariablesInPipeline(runPipelineObj);
1349
+ let hiddenFields = self.generateHiddenFields(resource, false);
1350
+ let toDo = {
1351
+ runAggregation: function (cb) {
1352
+ self
1353
+ .sanitisePipeline(runPipelineObj, hiddenFields, queryObj, req)
1354
+ .then((runPipelineObj) => {
1355
+ resource.model
1356
+ .aggregate(runPipelineObj)
1357
+ .then((results) => {
1358
+ cb(null, results);
1359
+ })
1360
+ .catch((err) => {
1361
+ cb(err);
1362
+ });
1363
+ })
1364
+ .catch((err) => {
1365
+ cb(err);
1366
+ });
1367
+ },
1368
+ };
1369
+ let translations = []; // array of form {ref:'lookupname',translations:[{value:xx, display:' '}]}
1370
+ // if we need to do any column translations add the function to the tasks list
1371
+ if (schema.columnTranslations) {
1372
+ toDo.applyTranslations = [
1373
+ "runAggregation",
1374
+ function (results, cb) {
1375
+ function doATranslate(column, theTranslation) {
1376
+ results["runAggregation"].forEach(function (resultRow) {
1377
+ let valToTranslate = resultRow[column.field];
1378
+ valToTranslate = valToTranslate
1379
+ ? valToTranslate.toString()
1380
+ : "";
1381
+ let thisTranslation = _.find(theTranslation.translations, function (option) {
1382
+ return valToTranslate === option.value.toString();
1383
+ });
1384
+ resultRow[column.field] = thisTranslation
1385
+ ? thisTranslation.display
1386
+ : " * Missing columnTranslation * ";
1387
+ });
1388
+ }
1389
+ schema.columnTranslations.forEach(function (columnTranslation) {
1390
+ if (columnTranslation.translations) {
1391
+ doATranslate(columnTranslation, columnTranslation);
1392
+ }
1393
+ if (columnTranslation.ref) {
1394
+ let theTranslation = _.find(translations, function (translation) {
1395
+ return translation.ref === columnTranslation.ref;
1396
+ });
1397
+ if (theTranslation) {
1398
+ doATranslate(columnTranslation, theTranslation);
1399
+ }
1400
+ else {
1401
+ cb("Invalid ref property of " +
1402
+ columnTranslation.ref +
1403
+ " in columnTranslations " +
1404
+ columnTranslation.field);
1405
+ }
1406
+ }
1407
+ });
1408
+ cb(null, null);
1409
+ },
1410
+ ];
1411
+ let callFuncs = false;
1412
+ for (let i = 0; i < schema.columnTranslations.length; i++) {
1413
+ let thisColumnTranslation = schema.columnTranslations[i];
1414
+ if (thisColumnTranslation.field) {
1415
+ // if any of the column translations are adhoc funcs, set up the tasks to perform them
1416
+ if (thisColumnTranslation.fn) {
1417
+ callFuncs = true;
1418
+ }
1419
+ // if this column translation is a "ref", set up the tasks to look up the values and populate the translations
1420
+ if (thisColumnTranslation.ref) {
1421
+ let lookup = self.getResource(thisColumnTranslation.ref);
1422
+ if (lookup) {
1423
+ if (!toDo[thisColumnTranslation.ref]) {
1424
+ let getFunc = function (ref) {
1425
+ let lookup = ref;
1426
+ return function (cb) {
1427
+ let translateObject = {
1428
+ ref: lookup.resourceName,
1429
+ translations: [],
1430
+ };
1431
+ translations.push(translateObject);
1432
+ lookup.model
1433
+ .find({}, {})
1434
+ .lean()
1435
+ .exec()
1436
+ .then((findResults) => {
1437
+ let j = 0;
1438
+ async.whilst(function (cbtest) {
1439
+ cbtest(null, j < findResults.length);
733
1440
  }, 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++;
1441
+ let theResult = findResults[j];
1442
+ translateObject.translations[j] =
1443
+ translateObject.translations[j] || {};
1444
+ let theTranslation = translateObject.translations[j];
1445
+ j++;
738
1446
  self.getListFields(lookup, theResult, function (err, description) {
739
1447
  if (err) {
740
1448
  cbres(err);
@@ -746,59 +1454,74 @@ DataForm.prototype.reportInternal = function (req, resource, schema, callback) {
746
1454
  }
747
1455
  });
748
1456
  }, cb);
749
- }
750
- });
1457
+ })
1458
+ .catch((err) => {
1459
+ cb(err);
1460
+ });
1461
+ };
751
1462
  };
752
- };
753
- toDo[thisColumnTranslation.ref] = getFunc(lookup);
754
- toDo.applyTranslations.unshift(thisColumnTranslation.ref); // Make sure we populate lookup before doing translation
1463
+ toDo[thisColumnTranslation.ref] = getFunc(lookup);
1464
+ toDo.applyTranslations.unshift(thisColumnTranslation.ref); // Make sure we populate lookup before doing translation
1465
+ }
1466
+ }
1467
+ else {
1468
+ return callback("Invalid ref property of " +
1469
+ thisColumnTranslation.ref +
1470
+ " in columnTranslations " +
1471
+ thisColumnTranslation.field);
755
1472
  }
756
1473
  }
757
- else {
758
- return callback('Invalid ref property of ' + thisColumnTranslation.ref + ' in columnTranslations ' + thisColumnTranslation.field);
1474
+ if (!thisColumnTranslation.translations &&
1475
+ !thisColumnTranslation.ref &&
1476
+ !thisColumnTranslation.fn) {
1477
+ return callback("A column translation needs a ref, fn or a translations property - " +
1478
+ thisColumnTranslation.field +
1479
+ " has neither");
759
1480
  }
760
1481
  }
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');
1482
+ else {
1483
+ return callback("A column translation needs a field property");
763
1484
  }
764
1485
  }
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);
1486
+ if (callFuncs) {
1487
+ toDo["callFunctions"] = [
1488
+ "runAggregation",
1489
+ function (results, cb) {
1490
+ async.each(results.runAggregation, function (row, cb) {
1491
+ for (let i = 0; i < schema.columnTranslations.length; i++) {
1492
+ let thisColumnTranslation = schema.columnTranslations[i];
1493
+ if (thisColumnTranslation.fn) {
1494
+ thisColumnTranslation.fn(row, cb);
1495
+ }
776
1496
  }
777
- }
778
- }, function () {
779
- cb(null);
780
- });
781
- }];
782
- toDo.applyTranslations.unshift('callFunctions'); // Make sure we do function before translating its result
1497
+ }, function () {
1498
+ cb(null);
1499
+ });
1500
+ },
1501
+ ];
1502
+ toDo.applyTranslations.unshift("callFunctions"); // Make sure we do function before translating its result
1503
+ }
783
1504
  }
1505
+ async.auto(toDo, function (err, results) {
1506
+ if (err) {
1507
+ callback(err);
1508
+ }
1509
+ else {
1510
+ callback(null, {
1511
+ success: true,
1512
+ schema: schema,
1513
+ report: results.runAggregation,
1514
+ paramsUsed: schema.params,
1515
+ });
1516
+ }
1517
+ });
784
1518
  }
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' };
1519
+ });
1520
+ }
1521
+ saveAndRespond(req, res, hiddenFields) {
1522
+ function internalSave(doc) {
1523
+ function decorateError(err) {
1524
+ let err2 = { status: "err" };
802
1525
  if (!err.errors) {
803
1526
  err2.message = err.message;
804
1527
  }
@@ -806,18 +1529,21 @@ DataForm.prototype.saveAndRespond = function (req, res, hiddenFields) {
806
1529
  extend(err2, err);
807
1530
  }
808
1531
  if (debug) {
809
- console.log('Error saving record: ' + JSON.stringify(err2));
1532
+ console.log("Error saving record: " + JSON.stringify(err2));
810
1533
  }
811
1534
  res.status(400).send(err2);
812
1535
  }
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++) {
1536
+ doc
1537
+ .save()
1538
+ .then((saved) => {
1539
+ saved = saved.toObject();
1540
+ for (const hiddenField in hiddenFields) {
1541
+ if (hiddenFields.hasOwnProperty(hiddenField) &&
1542
+ hiddenFields[hiddenField]) {
1543
+ let parts = hiddenField.split(".");
1544
+ let lastPart = parts.length - 1;
1545
+ let target = saved;
1546
+ for (let i = 0; i < lastPart; i++) {
821
1547
  if (target.hasOwnProperty(parts[i])) {
822
1548
  target = target[parts[i]];
823
1549
  }
@@ -827,360 +1553,746 @@ DataForm.prototype.saveAndRespond = function (req, res, hiddenFields) {
827
1553
  }
828
1554
  }
829
1555
  }
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);
1556
+ if (doc.__toClient) {
1557
+ /* Use this to pass anything back to the client that is not saved in the record
1558
+ Possible use case - sent a message saying that since this data has changed in a
1559
+ particular way the user should consider doing something else
1560
+ */
1561
+ saved.__toClient = doc.__toClient;
1562
+ }
1563
+ res.send(saved);
1564
+ })
1565
+ .catch((err) => {
1566
+ if (req.resource.options.onSaveError) {
1567
+ req.resource.options.onSaveError(err, req, res)
1568
+ .then(() => {
1569
+ decorateError(err);
1570
+ });
879
1571
  }
880
1572
  else {
881
- res.send(docs);
1573
+ decorateError(err);
882
1574
  }
883
1575
  });
884
1576
  }
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) {
1577
+ let doc = req.doc;
1578
+ if (typeof req.resource.options.onSave === "function") {
1579
+ req.resource.options.onSave(doc, req, function (err) {
905
1580
  if (err) {
906
1581
  throw err;
907
1582
  }
908
- else {
909
- stashAggregationResults = aggregationResults;
910
- cb(_.map(aggregationResults, function (obj) {
911
- return obj._id;
912
- }));
913
- }
1583
+ internalSave(doc);
914
1584
  });
915
1585
  }
916
1586
  else {
917
- cb([]);
1587
+ internalSave(doc);
918
1588
  }
919
1589
  }
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 });
1590
+ /**
1591
+ * All entities REST functions have to go through this first.
1592
+ */
1593
+ processCollection(req) {
1594
+ req.resource = this.getResource(req.params.resourceName);
1595
+ }
1596
+ /**
1597
+ * Renders a view with the list of docs, which may be modified by query parameters
1598
+ */
1599
+ collectionGet() {
1600
+ return _.bind(function (req, res, next) {
1601
+ this.processCollection(req);
1602
+ if (!req.resource) {
1603
+ return next();
1604
+ }
1605
+ if (typeof req.query === "undefined") {
1606
+ req.query = {};
1607
+ }
1608
+ try {
1609
+ const aggregationParam = req.query.a ? JSON.parse(req.query.a) : null;
1610
+ const findParam = req.query.f ? JSON.parse(req.query.f) : {};
1611
+ const projectParam = req.query.p ? JSON.parse(req.query.p) : {};
1612
+ const limitParam = req.query.l ? JSON.parse(req.query.l) : 0;
1613
+ const skipParam = req.query.s ? JSON.parse(req.query.s) : 0;
1614
+ const orderParam = req.query.o
1615
+ ? JSON.parse(req.query.o)
1616
+ : req.resource.options.listOrder;
1617
+ // Dates in aggregation must be Dates
1618
+ if (aggregationParam) {
1619
+ this.hackVariablesInPipeline(aggregationParam);
932
1620
  }
1621
+ const self = this;
1622
+ this.filteredFind(req.resource, req, aggregationParam, findParam, projectParam, orderParam, limitParam, skipParam, function (err, docs) {
1623
+ if (err) {
1624
+ return self.renderError(err, null, req, res);
1625
+ }
1626
+ else {
1627
+ res.send(docs);
1628
+ }
1629
+ });
1630
+ }
1631
+ catch (e) {
1632
+ res.status(400).send(e.message);
933
1633
  }
934
- doAggregation(function (idArray) {
935
- if (aggregationParam && idArray.length === 0) {
936
- callback(null, []);
1634
+ }, this);
1635
+ }
1636
+ generateProjection(hiddenFields, projectParam) {
1637
+ let type;
1638
+ function setSelectType(typeChar, checkChar) {
1639
+ if (type === checkChar) {
1640
+ throw new Error("Cannot mix include and exclude fields in select");
1641
+ }
1642
+ else {
1643
+ type = typeChar;
1644
+ }
1645
+ }
1646
+ let retVal = hiddenFields;
1647
+ if (projectParam) {
1648
+ let projection = Object.keys(projectParam);
1649
+ if (projection.length > 0) {
1650
+ projection.forEach((p) => {
1651
+ if (projectParam[p] === 0) {
1652
+ setSelectType("E", "I");
1653
+ }
1654
+ else if (projectParam[p] === 1) {
1655
+ setSelectType("I", "E");
1656
+ }
1657
+ else {
1658
+ throw new Error("Invalid projection: " + projectParam);
1659
+ }
1660
+ });
1661
+ if (type && type === "E") {
1662
+ // We are excluding fields - can just merge with hiddenFields
1663
+ Object.assign(retVal, projectParam, hiddenFields);
937
1664
  }
938
1665
  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
- });
1666
+ // We are selecting fields - make sure none are hidden
1667
+ retVal = projectParam;
1668
+ for (let h in hiddenFields) {
1669
+ if (hiddenFields.hasOwnProperty(h)) {
1670
+ delete retVal[h];
967
1671
  }
968
- callback(err, docs);
969
- });
1672
+ }
970
1673
  }
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.');
1674
+ }
984
1675
  }
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;
1676
+ return retVal;
1011
1677
  }
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);
1678
+ doFindFunc(req, resource, cb) {
1679
+ // filter out records the user has no access to unless we are just asking for list attributes
1680
+ if (resource.options.findFunc &&
1681
+ req?.route?.path !== "/api/:resourceName/:id/list") {
1682
+ resource.options.findFunc(req, cb);
1028
1683
  }
1029
1684
  else {
1030
- var idSel = { _id: id };
1031
- var crit = queryObj ? extend(queryObj, idSel) : idSel;
1032
- cb(null, resource.model.findOne(crit).select(hiddenFields));
1685
+ cb(null);
1033
1686
  }
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
1687
  }
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) {
1688
+ async doFindFuncPromise(req, resource) {
1689
+ return new Promise((resolve, reject) => {
1690
+ this.doFindFunc(req, resource, (err, queryObj) => {
1054
1691
  if (err) {
1055
- return res.send({
1056
- success: false,
1057
- err: util.inspect(err)
1058
- });
1692
+ reject(err);
1059
1693
  }
1060
- else if (doc == null) {
1061
- return res.send({
1062
- success: false,
1063
- err: 'Record not found'
1064
- });
1694
+ else {
1695
+ resolve(queryObj);
1065
1696
  }
1066
- req.doc = doc;
1067
- next();
1068
1697
  });
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);
1698
+ });
1699
+ }
1700
+ async filteredFind(resource, req, aggregationParam, findParam, projectParam, sortOrder, limit, skip, callback) {
1701
+ const that = this;
1702
+ let hiddenFields = this.generateHiddenFields(resource, false);
1703
+ let stashAggregationResults;
1704
+ async function doAggregation(queryObj, cb) {
1705
+ if (aggregationParam) {
1706
+ aggregationParam = await that.sanitisePipeline(aggregationParam, hiddenFields, queryObj, req);
1707
+ resource.model
1708
+ .aggregate(aggregationParam)
1709
+ .then((aggregationResults) => {
1710
+ stashAggregationResults = aggregationResults;
1711
+ cb(_.map(aggregationResults, function (obj) {
1712
+ return obj._id;
1713
+ }));
1714
+ })
1715
+ .catch((err) => {
1716
+ throw err;
1086
1717
  });
1087
1718
  }
1088
1719
  else {
1089
- return res.send(req.doc);
1720
+ cb([]);
1090
1721
  }
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);
1722
+ }
1723
+ that.doFindFunc(req, resource, function (err, queryObj) {
1724
+ if (err) {
1725
+ callback(err);
1101
1726
  }
1102
1727
  else {
1103
- record[name] = value;
1728
+ doAggregation(queryObj, function (idArray) {
1729
+ if (aggregationParam && idArray.length === 0) {
1730
+ callback(null, []);
1731
+ }
1732
+ else {
1733
+ let query = resource.model.find(queryObj);
1734
+ if (idArray.length > 0) {
1735
+ query = query.where("_id").in(idArray);
1736
+ }
1737
+ if (findParam) {
1738
+ query = query.find(findParam);
1739
+ }
1740
+ query = query.select(that.generateProjection(hiddenFields, projectParam));
1741
+ if (limit) {
1742
+ query = query.limit(limit);
1743
+ }
1744
+ if (skip) {
1745
+ query = query.skip(skip);
1746
+ }
1747
+ if (sortOrder) {
1748
+ query = query.sort(sortOrder);
1749
+ }
1750
+ query
1751
+ .exec()
1752
+ .then((docs) => {
1753
+ if (stashAggregationResults) {
1754
+ for (const obj of docs) {
1755
+ // Add any fields from the aggregation results whose field name starts __ to the mongoose Document
1756
+ let aggObj = stashAggregationResults.find((a) => a._id.toString() === obj._id.toString());
1757
+ for (const k of Object.keys(aggObj).filter((k) => k.startsWith("__"))) {
1758
+ obj[k] = aggObj[k];
1759
+ }
1760
+ }
1761
+ }
1762
+ callback(null, docs);
1763
+ })
1764
+ .catch((err) => {
1765
+ callback(err);
1766
+ });
1767
+ }
1768
+ });
1104
1769
  }
1105
1770
  });
1106
- delete record._replacingHiddenFields;
1107
1771
  }
1108
- };
1109
- DataForm.prototype.entityPut = function () {
1110
- return _.bind(function (req, res, next) {
1111
- var that = this;
1112
- this.processEntity(req, res, function () {
1772
+ collectionPost() {
1773
+ return _.bind(function (req, res, next) {
1774
+ this.processCollection(req);
1113
1775
  if (!req.resource) {
1114
1776
  next();
1115
1777
  return;
1116
1778
  }
1117
1779
  if (!req.body) {
1118
- throw new Error('Nothing submitted.');
1780
+ throw new Error("Nothing submitted.");
1119
1781
  }
1120
- var cleansedBody = that.cleanseRequest(req);
1121
- // Merge
1122
- _.each(cleansedBody, function (value, name) {
1123
- req.doc[name] = (value === '') ? undefined : value;
1782
+ let cleansedBody = this.cleanseRequest(req);
1783
+ req.doc = new req.resource.model(cleansedBody);
1784
+ this.saveAndRespond(req, res);
1785
+ }, this);
1786
+ }
1787
+ /**
1788
+ * Generate an object of fields to not expose
1789
+ **/
1790
+ generateHiddenFields(resource, state) {
1791
+ let hiddenFields = {};
1792
+ if (resource.options["hide"] !== undefined) {
1793
+ resource.options.hide.forEach(function (dt) {
1794
+ hiddenFields[dt] = state;
1124
1795
  });
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);
1796
+ }
1797
+ return hiddenFields;
1798
+ }
1799
+ /** Sec issue
1800
+ * Cleanse incoming data to avoid overwrite and POST request forgery
1801
+ * (name may seem weird but it was in French, so it is some small improvement!)
1802
+ */
1803
+ cleanseRequest(req) {
1804
+ let reqData = req.body, resource = req.resource;
1805
+ if (typeof resource.options["hide"] === "undefined") {
1806
+ return reqData;
1807
+ }
1808
+ let hiddenFields = resource.options.hide;
1809
+ _.each(reqData, function (num, key) {
1810
+ _.each(hiddenFields, function (fi) {
1811
+ if (fi === key) {
1812
+ delete reqData[key];
1813
+ }
1814
+ });
1815
+ });
1816
+ return reqData;
1817
+ }
1818
+ generateQueryForEntity(req, resource, id, cb) {
1819
+ let that = this;
1820
+ let hiddenFields = this.generateHiddenFields(resource, false);
1821
+ that.doFindFunc(req, resource, function (err, queryObj) {
1822
+ if (err) {
1823
+ cb(err);
1824
+ }
1825
+ else {
1826
+ const idSel = { _id: id };
1827
+ let crit;
1828
+ if (queryObj) {
1829
+ if (queryObj._id) {
1830
+ crit = { $and: [idSel, { _id: queryObj._id }] };
1831
+ delete queryObj._id;
1832
+ if (Object.keys(queryObj).length > 0) {
1833
+ crit = extend(crit, queryObj);
1834
+ }
1835
+ }
1836
+ else {
1837
+ crit = extend(queryObj, idSel);
1838
+ }
1839
+ }
1840
+ else {
1841
+ crit = idSel;
1842
+ }
1843
+ cb(null, resource.model
1844
+ .findOne(crit)
1845
+ .select(that.generateProjection(hiddenFields, req.query?.p)));
1846
+ }
1847
+ });
1848
+ }
1849
+ /*
1850
+ * Entity request goes here first
1851
+ * It retrieves the resource
1852
+ */
1853
+ processEntity(req, res, next) {
1854
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
1855
+ return next();
1856
+ }
1857
+ this.generateQueryForEntity(req, req.resource, req.params.id, function (err, query) {
1858
+ if (err) {
1859
+ return res.status(500).send({
1860
+ success: false,
1861
+ err: util.inspect(err),
1131
1862
  });
1132
1863
  }
1133
1864
  else {
1134
- that.saveAndRespond(req, res);
1865
+ query
1866
+ .exec()
1867
+ .then((doc) => {
1868
+ if (doc) {
1869
+ req.doc = doc;
1870
+ return next();
1871
+ }
1872
+ else {
1873
+ return res.status(404).send({
1874
+ success: false,
1875
+ err: "Record not found",
1876
+ });
1877
+ }
1878
+ })
1879
+ .catch((err) => {
1880
+ return res.status(400).send({
1881
+ success: false,
1882
+ err: util.inspect(err),
1883
+ });
1884
+ });
1135
1885
  }
1136
1886
  });
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 });
1887
+ }
1888
+ /**
1889
+ * Gets a single entity
1890
+ *
1891
+ * @return {Function} The function to use as route
1892
+ */
1893
+ entityGet() {
1894
+ return _.bind(function (req, res, next) {
1895
+ this.processEntity(req, res, function () {
1896
+ if (!req.resource) {
1897
+ return next();
1898
+ }
1899
+ if (req.resource.options.onAccess) {
1900
+ req.resource.options.onAccess(req, function () {
1901
+ return res.status(200).send(req.doc);
1902
+ });
1903
+ }
1904
+ else {
1905
+ return res.status(200).send(req.doc);
1145
1906
  }
1146
- return res.send({ success: true });
1147
1907
  });
1908
+ }, this);
1909
+ }
1910
+ replaceHiddenFields(record, data) {
1911
+ const self = this;
1912
+ if (record) {
1913
+ record._replacingHiddenFields = true;
1914
+ _.each(data, function (value, name) {
1915
+ // Only recurse into plain (sub-document) objects - Dates, ObjectIds etc are leaf values that
1916
+ // must be restored as-is, otherwise a secure Date field is silently dropped on every PUT
1917
+ if (_.isPlainObject(value)) {
1918
+ self.replaceHiddenFields(record[name], value);
1919
+ }
1920
+ else if (!record[name]) {
1921
+ record[name] = value;
1922
+ }
1923
+ });
1924
+ delete record._replacingHiddenFields;
1148
1925
  }
1149
- this.processEntity(req, res, function () {
1150
- if (!req.resource) {
1151
- next();
1152
- return;
1926
+ }
1927
+ entityPut() {
1928
+ return _.bind(function (req, res, next) {
1929
+ const that = this;
1930
+ this.processEntity(req, res, function () {
1931
+ if (!req.resource) {
1932
+ next();
1933
+ return;
1934
+ }
1935
+ if (!req.body) {
1936
+ throw new Error("Nothing submitted.");
1937
+ }
1938
+ let cleansedBody = that.cleanseRequest(req);
1939
+ // Merge
1940
+ for (let prop in cleansedBody) {
1941
+ if (cleansedBody.hasOwnProperty(prop)) {
1942
+ req.doc.set(prop, cleansedBody[prop] === "" ? undefined : cleansedBody[prop]);
1943
+ }
1944
+ }
1945
+ if (req.resource.options.hide !== undefined) {
1946
+ let hiddenFields = that.generateHiddenFields(req.resource, true);
1947
+ hiddenFields._id = false;
1948
+ req.resource.model
1949
+ .findById(req.doc._id, hiddenFields)
1950
+ .lean()
1951
+ .exec()
1952
+ .then((data) => {
1953
+ that.replaceHiddenFields(req.doc, data);
1954
+ that.saveAndRespond(req, res, hiddenFields);
1955
+ })
1956
+ .catch((err) => {
1957
+ throw err; // not sure if this is the right thing to do - didn't have any error-handing here in earlier version
1958
+ });
1959
+ }
1960
+ else {
1961
+ that.saveAndRespond(req, res);
1962
+ }
1963
+ });
1964
+ }, this);
1965
+ }
1966
+ generateDependencyList(resource) {
1967
+ if (resource.options.dependents === undefined) {
1968
+ let that = this;
1969
+ resource.options.dependents = that.resources.reduce(function (acc, r) {
1970
+ function searchPaths(schema, prefix) {
1971
+ let fldList = [];
1972
+ for (let fld in schema.paths) {
1973
+ if (schema.paths.hasOwnProperty(fld)) {
1974
+ const parts = fld.split(".");
1975
+ let schemaType = schema.tree;
1976
+ while (parts.length > 0) {
1977
+ schemaType = schemaType[parts.shift()];
1978
+ }
1979
+ if (schemaType.type) {
1980
+ if (schemaType.type.name === "ObjectId" &&
1981
+ schemaType.ref === resource.resourceName) {
1982
+ fldList.push(prefix + fld);
1983
+ }
1984
+ else if (_.isArray(schemaType.type)) {
1985
+ schemaType.type.forEach(function (t) {
1986
+ searchPaths(t, prefix + fld + ".");
1987
+ });
1988
+ }
1989
+ }
1990
+ }
1991
+ }
1992
+ if (fldList.length > 0) {
1993
+ acc.push({ resource: r, keys: fldList });
1994
+ }
1995
+ }
1996
+ searchPaths(r.model.schema, "");
1997
+ return acc;
1998
+ }, []);
1999
+ for (let pluginName in that.options.plugins) {
2000
+ let thisPlugin = that.options.plugins[pluginName];
2001
+ if (thisPlugin.dependencyChecks &&
2002
+ thisPlugin.dependencyChecks[resource.resourceName]) {
2003
+ resource.options.dependents = resource.options.dependents.concat(thisPlugin.dependencyChecks[resource.resourceName]);
2004
+ }
1153
2005
  }
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;
2006
+ }
2007
+ }
2008
+ async getDependencies(resource, id) {
2009
+ this.generateDependencyList(resource);
2010
+ let promises = [];
2011
+ let foreignKeyList = [];
2012
+ resource.options.dependents.forEach((collection) => {
2013
+ collection.keys.forEach((key) => {
2014
+ promises.push({
2015
+ p: collection.resource.model
2016
+ .find({ [key]: id })
2017
+ .limit(1)
2018
+ .exec(),
2019
+ collection,
2020
+ key,
2021
+ });
2022
+ });
2023
+ });
2024
+ return Promise.all(promises.map((p) => p.p)).then((results) => {
2025
+ results.forEach((r, i) => {
2026
+ if (r.length > 0) {
2027
+ foreignKeyList.push({
2028
+ resourceName: promises[i].collection.resource.resourceName,
2029
+ key: promises[i].key,
2030
+ id: r[0]._id,
2031
+ });
2032
+ }
2033
+ });
2034
+ return foreignKeyList;
2035
+ });
2036
+ }
2037
+ entityDelete() {
2038
+ let that = this;
2039
+ return _.bind(async function (req, res, next) {
2040
+ async function removeDoc(doc, resource) {
2041
+ switch (resource.options.handleRemove) {
2042
+ case "allow":
2043
+ // old behaviour - no attempt to maintain data integrity
2044
+ return doc.deleteOne();
2045
+ case "cascade":
2046
+ res.status(400).send('"cascade" option not yet supported');
2047
+ break;
2048
+ default:
2049
+ return that
2050
+ .getDependencies(resource, doc._id)
2051
+ .then((dependencies) => {
2052
+ if (dependencies.length > 0) {
2053
+ throw new ForeignKeyError(resource.resourceName, dependencies);
2054
+ }
2055
+ return doc.deleteOne();
2056
+ });
2057
+ }
2058
+ }
2059
+ async function runDeletion(doc, resource) {
2060
+ return new Promise((resolve) => {
2061
+ if (resource.options.onRemove) {
2062
+ resource.options.onRemove(doc, req, async function (err) {
2063
+ if (err) {
2064
+ throw err;
2065
+ }
2066
+ resolve(removeDoc(doc, resource));
2067
+ });
2068
+ }
2069
+ else {
2070
+ resolve(removeDoc(doc, resource));
1159
2071
  }
1160
- internalRemove(doc);
1161
2072
  });
1162
2073
  }
2074
+ this.processEntity(req, res, async function () {
2075
+ if (!req.resource) {
2076
+ next();
2077
+ return;
2078
+ }
2079
+ let doc = req.doc;
2080
+ try {
2081
+ void (await runDeletion(doc, req.resource));
2082
+ res.status(200).send();
2083
+ }
2084
+ catch (e) {
2085
+ if (e instanceof ForeignKeyError) {
2086
+ res.status(400).send(e.message);
2087
+ }
2088
+ else {
2089
+ res.status(500).send(e.message);
2090
+ }
2091
+ }
2092
+ });
2093
+ }, this);
2094
+ }
2095
+ entityList() {
2096
+ return _.bind(function (req, res, next) {
2097
+ const that = this;
2098
+ this.processEntity(req, res, function () {
2099
+ if (!req.resource) {
2100
+ return next();
2101
+ }
2102
+ const returnRawParam = req.query?.returnRaw
2103
+ ? !!JSON.parse(req.query.returnRaw)
2104
+ : false;
2105
+ if (returnRawParam) {
2106
+ const result = { _id: req.doc._id };
2107
+ for (const field of req.resource.options.listFields) {
2108
+ result[field.field] = req.doc[field.field];
2109
+ }
2110
+ return res.send(result);
2111
+ }
2112
+ else {
2113
+ that.getListFields(req.resource, req.doc, function (err, display) {
2114
+ if (err) {
2115
+ return res.status(500).send(err);
2116
+ }
2117
+ else {
2118
+ return res.send({ list: display });
2119
+ }
2120
+ });
2121
+ }
2122
+ });
2123
+ }, this);
2124
+ }
2125
+ // To disambiguate the contents of items - assumed to be the results of a single resource lookup or search -
2126
+ // pass the result of this function as the second argument to the disambiguate() function.
2127
+ // equalityProps should identify the property(s) of the items that must ALL be equal for two items to
2128
+ // be considered ambiguous.
2129
+ // disambiguationResourceName should identify the resource whose list field(s) should be used to generate
2130
+ // the disambiguation text for ambiguous results later.
2131
+ buildSingleResourceAmbiguousRecordStore(items, equalityProps, disambiguationResourceName) {
2132
+ const ambiguousResults = [];
2133
+ for (let i = 0; i < items.length - 1; i++) {
2134
+ for (let j = i + 1; j < items.length; j++) {
2135
+ if (!equalityProps.some((p) => items[i][p] !== items[j][p])) {
2136
+ if (!ambiguousResults.includes(items[i])) {
2137
+ ambiguousResults.push(items[i]);
2138
+ }
2139
+ if (!ambiguousResults.includes(items[j])) {
2140
+ ambiguousResults.push(items[j]);
2141
+ }
2142
+ }
2143
+ }
2144
+ }
2145
+ return { [disambiguationResourceName]: ambiguousResults };
2146
+ }
2147
+ // An alternative to buildSingleResourceAmbiguousRecordStore() for use when disambiguating the results of a
2148
+ // multi-resource lookup or search. In this case, all items need to include the name of the resource that
2149
+ // will be used (when necessary) to yield their disambiguation text later. The property of items that holds
2150
+ // that resource name should be identified by the disambiguationResourceNameProp parameter.
2151
+ // The scary-looking templating used here ensures that the items really do all have an (optional) string
2152
+ // property with the name identified by disambiguationResourceNameProp. For the avoidance of doubt, "prop"
2153
+ // here could be anything - "foo in f" would achieve the same result.
2154
+ buildMultiResourceAmbiguousRecordStore(items, equalityProps, disambiguationResourceNameProp) {
2155
+ const store = {};
2156
+ for (let i = 0; i < items.length - 1; i++) {
2157
+ for (let j = i + 1; j < items.length; j++) {
2158
+ if (items[i][disambiguationResourceNameProp] &&
2159
+ items[i][disambiguationResourceNameProp] ===
2160
+ items[j][disambiguationResourceNameProp] &&
2161
+ !equalityProps.some((p) => items[i][p] !== items[j][p])) {
2162
+ if (!store[items[i][disambiguationResourceNameProp]]) {
2163
+ store[items[i][disambiguationResourceNameProp]] = [];
2164
+ }
2165
+ if (!store[items[i][disambiguationResourceNameProp]].includes(items[i])) {
2166
+ store[items[i][disambiguationResourceNameProp]].push(items[i]);
2167
+ }
2168
+ if (!store[items[i][disambiguationResourceNameProp]].includes(items[j])) {
2169
+ store[items[i][disambiguationResourceNameProp]].push(items[j]);
2170
+ }
2171
+ }
2172
+ }
2173
+ }
2174
+ return store;
2175
+ }
2176
+ // return just the id and list fields for all of the records from req.resource.
2177
+ // list fields are those whose schema entry has a value for the "list" attribute (except where this is { ref: true })
2178
+ // if the resource has no explicit list fields identified, the first string field will be returned. if the resource
2179
+ // doesn't have any string fields either, the first (non-id) field will be returned.
2180
+ // usually, we will respond with an array of ILookupItem objects, where the .text property of those objects is the concatenation
2181
+ // of all of the document's list fields (space-seperated).
2182
+ // to request the documents without this transformation applied, include "c=true" in the query string.
2183
+ // the query string can also be used to filter and order the response, by providing values for "f" (find), "l" (limit),
2184
+ // "s" (skip) and/or "o" (order).
2185
+ // results will be disambiguated if req.resource includes disambiguation parameters in its resource options.
2186
+ // where c=true, the disambiguation will be added as a suffix to the .text property of the returned ILookupItem objects.
2187
+ // otherwise, if the resource has just one list field, the disambiguation will be appended to the values of that field, and if
2188
+ // it has multiple list fields, it will be returned as an additional property of the returned (untransformed) objects
2189
+ internalEntityListAll(req, callback) {
2190
+ const projection = this.generateListFieldProjection(req.resource);
2191
+ const listFields = Object.keys(projection);
2192
+ const aggregationParam = req.query.a ? JSON.parse(req.query.a) : null;
2193
+ const findParam = req.query.f ? JSON.parse(req.query.f) : {};
2194
+ const limitParam = req.query.l ? JSON.parse(req.query.l) : 0;
2195
+ const skipParam = req.query.s ? JSON.parse(req.query.s) : 0;
2196
+ const orderParam = req.query.o
2197
+ ? JSON.parse(req.query.o)
2198
+ : req.resource.options.listOrder;
2199
+ const concatenateParam = req.query.c ? JSON.parse(req.query.c) : true;
2200
+ const resOpts = req.resource.options;
2201
+ let disambiguationField;
2202
+ let disambiguationResourceName;
2203
+ if (resOpts?.disambiguation) {
2204
+ disambiguationField = resOpts.disambiguation.field;
2205
+ if (disambiguationField) {
2206
+ projection[disambiguationField] = 1;
2207
+ disambiguationResourceName = resOpts.disambiguation.resource;
2208
+ }
2209
+ }
2210
+ const that = this;
2211
+ this.filteredFind(req.resource, req, aggregationParam, findParam, projection, orderParam, limitParam, skipParam, function (err, docs) {
2212
+ if (err) {
2213
+ return callback(err);
2214
+ }
1163
2215
  else {
1164
- internalRemove(doc);
2216
+ docs = docs.map((d) => d.toObject());
2217
+ if (concatenateParam) {
2218
+ const transformed = docs.map((doc) => {
2219
+ let text = "";
2220
+ for (const field of listFields) {
2221
+ if (doc[field]) {
2222
+ if (text !== "") {
2223
+ text += " ";
2224
+ }
2225
+ text += doc[field];
2226
+ }
2227
+ }
2228
+ const disambiguationId = disambiguationField
2229
+ ? doc[disambiguationField]
2230
+ : undefined;
2231
+ return { id: doc._id, text, disambiguationId };
2232
+ });
2233
+ if (disambiguationResourceName) {
2234
+ that.disambiguate(transformed, that.buildSingleResourceAmbiguousRecordStore(transformed, ["text"], disambiguationResourceName), "disambiguationId", (item, disambiguationText) => {
2235
+ item.text += ` (${disambiguationText})`;
2236
+ }, (err) => {
2237
+ callback(err, transformed);
2238
+ });
2239
+ }
2240
+ else {
2241
+ return callback(null, transformed);
2242
+ }
2243
+ }
2244
+ else {
2245
+ if (disambiguationResourceName) {
2246
+ that.disambiguate(docs, that.buildSingleResourceAmbiguousRecordStore(docs, listFields, disambiguationResourceName), disambiguationField, (item, disambiguationText) => {
2247
+ if (listFields.length === 1) {
2248
+ item[listFields[0]] += ` (${disambiguationText})`;
2249
+ }
2250
+ else {
2251
+ // store the text against hard-coded property name "disambiguation", rather than (say) using
2252
+ // item[disambiguationResourceName], because if disambiguationResourceName === disambiguationField,
2253
+ // that value would end up being deleted again when the this.disambiguate() call (which we have
2254
+ // been called from) does its final tidy-up and deletes [disambiguationField] from all of the items in docs
2255
+ item.disambiguation = disambiguationText;
2256
+ }
2257
+ }, (err) => {
2258
+ callback(err, docs);
2259
+ });
2260
+ }
2261
+ else {
2262
+ return callback(null, docs);
2263
+ }
2264
+ }
1165
2265
  }
1166
2266
  });
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) {
2267
+ }
2268
+ entityListAll() {
2269
+ return _.bind(function (req, res, next) {
2270
+ if (!(req.resource = this.getResource(req.params.resourceName))) {
1174
2271
  return next();
1175
2272
  }
1176
- that.getListFields(req.resource, req.doc, function (err, display) {
2273
+ this.internalEntityListAll(req, function (err, resultsObject) {
1177
2274
  if (err) {
1178
- return res.status(500).send(err);
2275
+ res.status(400, err);
1179
2276
  }
1180
2277
  else {
1181
- return res.send({ list: display });
2278
+ res.send(resultsObject);
1182
2279
  }
1183
2280
  });
1184
- });
1185
- }, this);
1186
- };
2281
+ }, this);
2282
+ }
2283
+ extractTimestampFromMongoID(record) {
2284
+ let timestamp = record.toString().substring(0, 8);
2285
+ return new Date(parseInt(timestamp, 16) * 1000);
2286
+ }
2287
+ }
2288
+ // Operators that run server-side JavaScript, which can read beyond the documents a findFunc allows. They are
2289
+ // rejected wherever they appear in a pipeline - as a stage, inside a $match, or nested in an expression.
2290
+ FormsAngular.forbiddenPipelineOperators = ["$where", "$function", "$accumulator"];
2291
+ export class ForeignKeyError extends global.Error {
2292
+ constructor(resourceName, foreignKeys) {
2293
+ super(`Cannot delete this ${resourceName}, as it is: ${foreignKeys.map((d) => ` the ${d.key} on ${d.resourceName} ${d.id}`).join("; ")}`);
2294
+ this.name = "ForeignKeyError";
2295
+ this.stack = new global.Error("").stack;
2296
+ }
2297
+ }
2298
+ export default FormsAngular;