From a7120f1ded94400aaa3a100c5097d675d82e92fc Mon Sep 17 00:00:00 2001 From: wedgwood Date: Mon, 6 Nov 2017 13:56:31 +0800 Subject: [PATCH] feature: multiple connections --- index.js | 25 +++++++++++++------ test.js | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 7 deletions(-) diff --git a/index.js b/index.js index 7332631..31949ca 100644 --- a/index.js +++ b/index.js @@ -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) { @@ -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') diff --git a/test.js b/test.js index 01f9579..3b11aac 100644 --- a/test.js +++ b/test.js @@ -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() + }) + }) +})