Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ function fastifyMongodb (fastify, options, next) {
const url = options.url
delete options.url

const name = options.name
delete options.name

MongoClient.connect(url, options, onConnect)

function onConnect (err, db) {
Expand All @@ -20,16 +23,24 @@ function fastifyMongodb (fastify, options, next) {
ObjectId: ObjectId
}

fastify
.decorate('mongo', mongo)
.addHook('onClose', close)
if (name) {
if (!fastify.mongo) {
fastify.decorate('mongo', {})
}

fastify.mongo[name] = mongo
} else {
if (fastify.mongo) {
next(new Error('fastify-mongo has already registered'))
} else {
fastify.mongo = mongo
}
}

fastify.addHook('onClose', (fastify, done) => db.close(done))

next()
}
}

function close (fastify, done) {
fastify.mongo.db.close(done)
}

module.exports = fp(fastifyMongodb, '>=0.13.1')
73 changes: 73 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,76 @@ test('fastify.mongo.db should be the mongo database client', t => {
})
})
})

test('fastify.mongo.test should exist', t => {
t.plan(5)

const fastify = Fastify()

fastify.register(fastifyMongo, {
name: 'test',
url: 'mongodb://127.0.0.1'
})

fastify.ready(err => {
t.error(err)
t.ok(fastify.mongo)
t.ok(fastify.mongo.test)
t.ok(fastify.mongo.test.db)
t.ok(fastify.mongo.test.ObjectId)

fastify.close()
})
})

test('fastify.mongo.test.ObjectId should be a mongo ObjectId', t => {
t.plan(5)

const fastify = Fastify()

fastify.register(fastifyMongo, {
name: 'test',
url: 'mongodb://127.0.0.1'
})

fastify.ready(err => {
t.error(err)

const obj1 = new fastify.mongo.test.ObjectId()
t.ok(obj1)

const obj2 = new fastify.mongo.test.ObjectId(obj1)
t.ok(obj2)
t.ok(obj1.equals(obj2))

const obj3 = new fastify.mongo.test.ObjectId()
t.notOk(obj1.equals(obj3))

fastify.close()
})
})

test('fastify.mongo.db should be the mongo database client', t => {
t.plan(3)

const fastify = Fastify()

fastify.register(fastifyMongo, {
name: 'test',
url: 'mongodb://127.0.0.1'
})

fastify.ready(err => {
t.error(err)

const db = fastify.mongo.test.db
const col = db.collection('test')

col.insertOne({ a: 1 }, (err, r) => {
t.error(err)
t.equal(1, r.insertedCount)

fastify.close()
})
})
})