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