forked from Techie-Qabila/fastify-mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (61 loc) · 1.5 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
63
64
65
66
67
68
69
70
71
72
73
'use strict'
const fp = require('fastify-plugin')
const mongoose = require('mongoose')
const ObjectId = mongoose.Types.ObjectId
function fastifyMongoose (fastify, options, next) {
const uri = options.uri
if (!uri) {
next(new Error('`uri` parameter is mandatory'))
return
}
delete options.uri
const name = options.name
if (name) {
delete options.name
}
const opt = {
...options,
useNewUrlParser: true,
useUnifiedTopology: true
}
mongoose.connect(uri, opt)
.then(db => {
mongoose.connection.on('error', err => {
fastify.log.error(err, 'Mongoose connection error')
})
fastify.addHook('onClose', function (fastify, done) {
mongoose.connection.close(done)
})
const mongo = {
db: db,
ObjectId: ObjectId
}
if (name) {
if (!fastify.mongo) {
fastify.decorate('mongo', mongo)
}
if (fastify.mongo[name]) {
next(new Error('Connection name already registered: ' + name))
return
}
fastify.mongo[name] = mongo
} else {
if (fastify.mongo) {
next(new Error('fastify-mongoose has already registered'))
return
}
}
if (!fastify.mongo) {
fastify.decorate('mongo', mongo)
}
next()
})
.catch(err => {
fastify.log.error(err, 'Error connecting to MongoDB')
next(err)
})
}
module.exports = fp(fastifyMongoose, {
fastify: '>=1.0.0',
name: 'fastify-mongoose'
})