-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
38 lines (32 loc) · 896 Bytes
/
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
'use strict'
const fastifyPlugin = require('fastify-plugin')
const MongoInMemory = require('mongo-in-memory')
const mongodb = require('mongodb')
function fastifyMongoMemory (fastify, opts, next) {
const server = new MongoInMemory(opts.port || 8000)
server.start(function (error) {
if (error) {
next(error)
} else {
const uri = server.getMongouri(opts.dbname || 'test')
mongodb.connect(uri, function (error, db) {
if (error) {
next(error)
} else {
fastify.decorate('mongo', { db, ObjectId: mongodb.ObjectID })
next()
}
})
}
})
fastify.addHook('onClose', function (instance, done) {
server.stop(function (error) {
if (error) {
done(error)
} else {
fastify.mongo.db.close(done)
}
})
})
}
module.exports = fastifyPlugin(fastifyMongoMemory, '>=0.30.0')