-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmongoHandler.js
335 lines (288 loc) · 10.1 KB
/
mongoHandler.js
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
"use strict";
var _ = {
omitBy: require("lodash.omitby")
};
var async = require("async");
var debug = require("./debugging");
var mongodb = require("mongodb");
var Joi = require("joi");
var semver = require("semver");
var MIN_SERVER_VERSION = "1.10.0";
var MongoStore = module.exports = function MongoStore(config) {
MongoStore._checkMinServerVersion();
this._config = config;
};
/**
Handlers readiness status. This should be set to `true` once all handlers are ready to process requests.
*/
MongoStore.prototype.ready = false;
MongoStore._checkMinServerVersion = function() {
var serverVersion = require('jsonapi-server')._version;
if (!serverVersion) return;
if (semver.lt(serverVersion, MIN_SERVER_VERSION)) {
throw new Error("This version of jsonapi-store-mongodb requires jsonapi-server>=" + MIN_SERVER_VERSION + ".");
}
};
MongoStore._mongoUuid = function(uuid) {
return new mongodb.Binary(uuid, mongodb.Binary.SUBTYPE_UUID);
};
MongoStore._isRelationshipAttribute = function(attribute) {
return attribute._settings && (attribute._settings.__one || attribute._settings.__many);
};
MongoStore._toMongoDocument = function(resource) {
var document = _.omitBy(resource, function(value) { return value === undefined; });
document._id = MongoStore._mongoUuid(document.id);
return document;
};
MongoStore._getRelationshipAttributeNames = function(attributes) {
var attributeNames = Object.getOwnPropertyNames(attributes);
var relationshipAttributeNames = attributeNames.reduce(function(partialAttributeNames, name) {
var attribute = attributes[name];
if (MongoStore._isRelationshipAttribute(attribute)) {
return partialAttributeNames.concat(name);
}
return partialAttributeNames;
}, []);
return relationshipAttributeNames;
};
MongoStore._filterElementToMongoExpr = function(filterElement) {
var value = filterElement.value;
if (!filterElement.operator) return value;
var mongoExpr = {
">": { $gt: value },
"<": { $lt: value },
"~": new RegExp("^" + value + "$", "i"),
":": new RegExp(value, "i")
}[filterElement.operator];
return mongoExpr;
};
MongoStore.prototype._getSearchCriteria = function(request) {
var self = this;
var filter = request.processedFilter;
if (!filter) return { };
var criteria = Object.keys(filter).map(function(attribute) {
var values = filter[attribute].map(MongoStore._filterElementToMongoExpr);
var attributeConfig = self.resourceConfig.attributes[attribute];
// Relationships need to be queried via .id
if (attributeConfig && attributeConfig._settings) {
attribute += ".id";
}
values = values.reduce(function(mongoExpressions, mongoExpr) {
if (mongoExpr !== null) {
var mongoExprForAttr = { };
mongoExprForAttr[attribute] = mongoExpr;
mongoExpressions.push(mongoExprForAttr);
}
return mongoExpressions;
}, []);
if (values.length === 0) {
return null;
}
if (values.length === 1) {
return values[0];
}
return { $or: values };
}).filter(function(value) {
return value !== null;
});
if (criteria.length === 0) {
return { };
}
if (criteria.length === 1) {
return criteria[0];
}
return { $and: criteria };
};
MongoStore._notFoundError = function(type, id) {
return {
status: "404",
code: "ENOTFOUND",
title: "Requested resource does not exist",
detail: "There is no " + type + " with id " + id
};
};
MongoStore._unknownError = function(err) {
return {
status: "500",
code: "EUNKNOWN",
title: "An unknown error has occured",
detail: err
};
};
MongoStore.prototype._createIndexesForRelationships = function(collection, relationshipAttributeNames) {
if (!Array.isArray(relationshipAttributeNames) || !relationshipAttributeNames.length) return;
relationshipAttributeNames.forEach(function(name) {
var keys = { };
keys[name + ".id"] = 1;
collection.createIndex(keys);
});
};
MongoStore.prototype._applySort = function(request, cursor) {
if (!request.params.sort) return cursor;
var attribute = request.params.sort;
var order = 1;
attribute = String(attribute);
if (attribute[0] === "-") {
order = -1;
attribute = attribute.substring(1, attribute.length);
}
var sortParam = { };
sortParam[attribute] = order;
return cursor.sort(sortParam);
};
MongoStore.prototype._applyPagination = function(request, cursor) {
if (!request.params.page) return cursor;
return cursor.skip(request.params.page.offset).limit(request.params.page.limit);
};
/**
Initialise gets invoked once for each resource that uses this handler.
*/
MongoStore.prototype.initialise = function(resourceConfig) {
var self = this;
if (!self._config.url) {
return console.error("MongoDB url missing from configuration");
}
self.resourceConfig = resourceConfig;
self.relationshipAttributeNames = MongoStore._getRelationshipAttributeNames(resourceConfig.attributes);
mongodb.MongoClient.connect(self._config.url, {
reconnectTries: 999999999,
reconnectInterval: 5000
}).then(function(db) {
self._db = db;
self._db.on("close", function(err) {
console.error("mongodb connection closed:", err.message);
self.ready = false;
self._db.collection("Nope").findOne({ _id: 0 }, { _id: 0 }, function() {
console.error("mongodb connection is back");
self.ready = true;
});
});
}).catch(function(err) {
console.error("mongodb connection failed:", err.message);
setTimeout(function() {
self.initialise(resourceConfig);
}, 5000);
}).then(function() {
var resourceName = resourceConfig.resource;
var collection = self._db.collection(resourceName);
self._createIndexesForRelationships(collection, self.relationshipAttributeNames);
self.ready = true;
});
};
/**
Drops the database if it already exists and populates it with example documents.
*/
MongoStore.prototype.populate = function(callback) {
var self = this;
if (!self._db) return;
self._db.dropDatabase(function(err) {
if (err) return console.error("error dropping database", err.message);
async.each(self.resourceConfig.examples, function(document, cb) {
var validationResult = Joi.validate(document, self.resourceConfig.attributes);
if (validationResult.error) {
return cb(validationResult.error);
}
self.create({ params: {} }, validationResult.value, cb);
}, function(error) {
if (error) console.error("error creating example document:", error);
return callback();
});
});
};
/**
Search for a list of resources, give a resource type.
*/
MongoStore.prototype.search = function(request, callback) {
var self = this;
var collection = self._db.collection(request.params.type);
var criteria = self._getSearchCriteria(request);
debug("search", JSON.stringify(criteria));
async.parallel({
resultSet: function(asyncCallback) {
var cursor = collection.find(criteria, { _id: 0 });
self._applySort(request, cursor);
self._applyPagination(request, cursor);
return cursor.toArray(asyncCallback);
},
totalRows: function(asyncCallback) {
return collection.find(criteria, { _id: 0 }).count(asyncCallback);
}
}, function(err, results) {
if (err) {
return callback(MongoStore._unknownError);
}
return callback(null, results.resultSet, results.totalRows);
});
};
/**
Find a specific resource, given a resource type and and id.
*/
MongoStore.prototype.find = function(request, callback) {
var collection = this._db.collection(request.params.type);
var documentId = MongoStore._mongoUuid(request.params.id);
debug("findOne", JSON.stringify({ _id: documentId }));
collection.findOne({ _id: documentId }, { _id: 0 }, function(err, result) {
if (err || !result) {
return callback(MongoStore._notFoundError(request.params.type, request.params.id));
}
return callback(null, result);
});
};
/**
Create (store) a new resource give a resource type and an object.
*/
MongoStore.prototype.create = function(request, newResource, callback) {
var collection = this._db.collection(newResource.type);
var document = MongoStore._toMongoDocument(newResource);
debug("insert", JSON.stringify(document));
collection.insertOne(document, function(err) {
if (err) return callback(MongoStore._unknownError(err));
collection.findOne(document, { _id: 0 }, function(findErr, result) {
if (findErr) return callback(err);
if (!result) return callback("Could not find document after insert");
return callback(null, result);
});
});
};
/**
Delete a resource, given a resource type and an id.
*/
MongoStore.prototype.delete = function(request, callback) {
var collection = this._db.collection(request.params.type);
var documentId = MongoStore._mongoUuid(request.params.id);
collection.deleteOne({ _id: documentId }, function(err, result) {
if (err) return callback(MongoStore._unknownError(err));
if (result.deletedCount === 0) {
return callback(MongoStore._notFoundError(request.params.type, request.params.id));
}
return callback(null, result);
});
};
/**
Update a resource, given a resource type and id, along with a partialResource.
partialResource contains a subset of changes that need to be merged over the original.
*/
MongoStore.prototype.update = function(request, partialResource, callback) {
var collection = this._db.collection(request.params.type);
var documentId = MongoStore._mongoUuid(request.params.id);
var partialDocument = _.omitBy(partialResource, function(value) { return value === undefined; });
debug("findOneAndUpdate", JSON.stringify(partialDocument));
collection.findOneAndUpdate({
_id: documentId
}, {
$set: partialDocument
}, {
returnOriginal: false,
projection: { _id: 0 }
}, function(err, result) {
if (err) {
debug("err", JSON.stringify(err));
return callback(MongoStore._unknownError(err));
}
if (!result || !result.value) {
return callback(MongoStore._notFoundError(request.params.type, request.params.id));
}
debug("result", JSON.stringify(result));
return callback(null, result.value);
});
};