forms-angular 0.12.0-beta.21 → 0.12.0-beta.211

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