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