-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathembedderHooks.js
More file actions
245 lines (194 loc) · 6.17 KB
/
embedderHooks.js
File metadata and controls
245 lines (194 loc) · 6.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
'use strict';
var utils = require('./utils');
var EmbeddedDocument = require('./embeddedDocument');
// this object is used to detect empty field in embedded docs wrapping
var empty = {};
var relationFieldRegExp = new RegExp(
'^' +
'[^\\.\\$]+(?:\\.\\$)?' +
'(?:' +
'\\.' +
'[^\\.\\$]+(?:\\.\\$)?' +
')*' +
'$'
);
var splitRelationField = function(field) {
if (!relationFieldRegExp.test(field)) {
throw new Error('Field "' + field + '" has wrong format');
}
var fieldParts = field.split('.');
return fieldParts.reduce(function(parts, part) {
var lastPart = parts[parts.length - 1];
if (!lastPart || lastPart === '$' || part === '$') {
parts.push(part);
} else {
parts[parts.length - 1] += '.' + part;
}
return parts;
}, []);
};
var wrapEmbeddedField = function(object, fieldParts, embedder, options) {
var fieldKeyPart = fieldParts[0];
var positionalPart = fieldParts[1];
var value = utils.deepGet(object, fieldKeyPart, empty);
if (value === empty) return;
if (positionalPart === '$') {
if (!Array.isArray(value)) {
throw new Error('Field `' + fieldKeyPart + '` should be an array');
}
var isLastPart = fieldParts.length <= 2;
value.forEach(function(item, index) {
if (isLastPart) {
value[index] = embedder(item, options);
} else {
if (!utils.isObject(value)) {
throw new Error(
'Array field `' + fieldKeyPart + '` should have objects as items'
);
}
wrapEmbeddedField(item, fieldParts.slice(2), embedder, options);
}
});
} else {
utils.deepSet(object, fieldKeyPart, embedder(value, options));
}
};
var getFindParamsHash = function(object) {
var findParamsHash = {};
var processObject = function(object) {
Object.keys(object).forEach(function(key) {
var value = object[key];
if (!Array.isArray(value) && !utils.isSimpleObject(value)) return;
if (value instanceof EmbeddedDocument) {
if (value.embeddedValue) return;
var uniqGroupId = value.getUniqGroupId();
var params = findParamsHash[uniqGroupId];
if (!params) {
params = findParamsHash[uniqGroupId] = {
key: value.key,
identifiers: [],
collection: value.collection,
projection: value.projection
};
}
params.identifiers.push(value.identifier);
} else {
processObject(value);
}
});
};
processObject(object);
return findParamsHash;
};
var getEmbeddedDocumentsHash = function(object, callback) {
var findParamsHash = getFindParamsHash(object);
var uniqGroupIds = Object.keys(findParamsHash);
var funcs = uniqGroupIds.map(function(uniqGroupId) {
return function(callback) {
var params = findParamsHash[uniqGroupId];
var projectionKeys = Object.keys(params.projection);
if (projectionKeys.length === 1 && params.projection[params.key]) {
var documents = params.identifiers.map(function(identifier) {
return utils.createObject(params.key, identifier);
});
callback(null, documents);
} else {
var condition = utils.createObject(params.key, {$in: params.identifiers});
params.collection.find(condition, params.projection).toArray(callback);
}
};
});
utils.asyncParallel(funcs, function(err, documentsGroups) {
if (err) return callback(err);
var documentsHash = {};
uniqGroupIds.forEach(function(uniqGroupId, index) {
var params = findParamsHash[uniqGroupId];
var documents = documentsGroups[index];
documentsHash[uniqGroupId] = utils.indexBy(documents, params.key);
});
callback(null, documentsHash);
});
};
var replaceEmbeddedDocuments = function(object, documentsHash) {
Object.keys(object).forEach(function(key) {
var value = object[key];
if (!Array.isArray(value) && !utils.isSimpleObject(value)) return;
if (value instanceof EmbeddedDocument) {
var uniqGroupId = value.getUniqGroupId();
var embeddedDocument = value.embeddedValue
? value.embeddedValue
: documentsHash[uniqGroupId][value.identifier];
if (!embeddedDocument) {
throw new Error(
'Document with ' + value.key + '=' + value.identifier +
' is not found in `' + value.collection.collectionName + '` collection'
);
}
object[key] = embeddedDocument;
} else {
replaceEmbeddedDocuments(value, documentsHash);
}
});
};
var processEmbeddedDocuments = function(object, relations, options, callback) {
try {
Object.keys(relations).forEach(function(field) {
var embedder = relations[field].embedder;
wrapEmbeddedField(object, splitRelationField(field), embedder, options);
});
getEmbeddedDocumentsHash(object, function(err, documentsHash) {
if (err) return callback(err);
try {
replaceEmbeddedDocuments(object, documentsHash);
} catch(err) {
return callback(err);
}
callback();
});
} catch(err) {
return callback(err);
}
};
var processOptions = function(params) {
var embedderOptions = {};
if ('trustEmbeddedValue' in params.options) {
embedderOptions.trustEmbeddedValue = params.options.trustEmbeddedValue;
delete params.options.trustEmbeddedValue;
}
return embedderOptions;
};
exports.setup = function(collection, relations) {
collection.on('beforeInsertOne', function(params, callback) {
var embedderOptions = processOptions(params);
processEmbeddedDocuments(params.obj, relations, embedderOptions, callback);
});
collection.on('beforeInsertMany', function(params, callback) {
var embedderOptions = processOptions(params);
utils.asyncParallel(params.objs.map(function(object) {
return function(callback) {
processEmbeddedDocuments(object, relations, embedderOptions, callback);
};
}), callback);
});
var beforeUpdate = function(params, callback) {
var object;
var embedderOptions = processOptions(params);
if (params.modifier) {
if (utils.isModifier(params.modifier)) {
if (params.modifier.$set) {
object = params.modifier.$set;
}
} else {
object = params.modifier;
}
} else if (params.replacement) {
object = params.replacement;
}
if (!object) return callback();
processEmbeddedDocuments(object, relations, embedderOptions, callback);
};
collection.on('beforeUpdateOne', beforeUpdate);
collection.on('beforeUpdateMany', beforeUpdate);
collection.on('beforeUpsertOne', beforeUpdate);
collection.on('beforeReplaceOne', beforeUpdate);
};