forms-angular 0.12.0-beta.37 → 0.12.0-beta.370

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