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