-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathindex.js
62 lines (42 loc) · 1.74 KB
/
index.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
'use strict';
const Hoek = require('@hapi/hoek');
const MongoModels = require('mongo-models');
const register = async function (server, options) {
Hoek.assert(options.models, 'options.models is required');
Hoek.assert(options.mongodb, 'options.mongodb is required');
Hoek.assert(options.mongodb.connection, 'options.mongodb.connection is required');
Hoek.assert(options.mongodb.connection.uri, 'options.mongodb.connection.uri is required');
const modelModules = options.models.reduce((accumulator, path) => {
accumulator[path] = require(path);
return accumulator;
}, {});
server.expose('mongo-models', MongoModels);
server.ext({
type: 'onPreStart',
method: async function (_server) {
if (options.hasOwnProperty('autoIndex') && options.autoIndex === false) {
return;
}
const indexJobs = options.models
.map((path) => modelModules[path])
.filter((model) => Boolean(model.indexes))
.map((model) => model.createIndexes(model.indexes));
await Promise.all(indexJobs);
server.log(['info', 'mongodb'], 'HapiMongoModels: finished processing auto indexes.');
}
});
server.ext({
type: 'onPostStop',
method: function (_server) {
MongoModels.disconnect();
server.log(['info', 'mongodb'], 'HapiMongoModels: closed db connection(s).');
}
});
await MongoModels.connect(options.mongodb.connection, options.mongodb.options);
server.log(['info', 'mongodb'], 'HapiMongoModels: successfully connected to the db.');
};
module.exports = {
name: 'hapi-mongo-models',
pkg: require('./package.json'),
register
};