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