-
Notifications
You must be signed in to change notification settings - Fork 51
/
index.js
87 lines (72 loc) · 1.94 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'use strict'
const fp = require('fastify-plugin')
const { MongoClient, ObjectId } = require('mongodb')
function decorateFastifyInstance (fastify, client, options) {
const { forceClose, database, name, newClient } = options
if (newClient) {
// done() is not needed because .close() returns a Promise
fastify.addHook('onClose', function closeMongoDb () {
return client.close(forceClose)
})
}
const mongo = {
client,
ObjectId
}
if (name) {
if (!fastify.mongo) {
fastify.decorate('mongo', mongo)
}
if (fastify.mongo[name]) {
throw Error('Connection name already registered: ' + name)
}
fastify.mongo[name] = mongo
} else {
if (fastify.mongo) {
throw Error('fastify-mongodb has already registered')
}
}
if (database) {
mongo.db = client.db(database)
}
if (!fastify.mongo) {
fastify.decorate('mongo', mongo)
}
}
async function fastifyMongodb (fastify, options) {
options = Object.assign({
serverSelectionTimeoutMS: 7500
}, options)
const { forceClose, name, database, url, client, ...opts } = options
if (client) {
decorateFastifyInstance(fastify, client, {
newClient: false,
forceClose,
database,
name
})
} else {
if (!url) {
throw Error('`url` parameter is mandatory if no client is provided')
}
const urlTokens = /\w\/([^?]*)/g.exec(url)
const parsedDbName = urlTokens && urlTokens[1]
const databaseName = database || parsedDbName
const client = new MongoClient(url, opts)
await client.connect()
decorateFastifyInstance(fastify, client, {
newClient: true,
forceClose,
database: databaseName,
name
})
}
}
module.exports = fp(fastifyMongodb, {
fastify: '5.x',
name: '@fastify/mongodb'
})
module.exports.default = fastifyMongodb
module.exports.fastifyMongodb = fastifyMongodb
module.exports.mongodb = require('mongodb')
module.exports.ObjectId = ObjectId