-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.js
49 lines (39 loc) · 1.28 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
'use strict'
const fp = require('fastify-plugin')
const { Client } = require('@elastic/elasticsearch')
const isElasticsearchClient = require('./lib/isElasticsearchClient')
async function fastifyElasticsearch (fastify, options) {
const { namespace, healthcheck } = options
delete options.namespace
delete options.healthcheck
const client = options.client || new Client(options)
if (healthcheck !== false) {
await client.ping()
}
if (namespace) {
if (!fastify.elastic) {
fastify.decorate('elastic', {})
}
if (fastify.elastic[namespace]) {
throw new Error(`Elasticsearch namespace already used: ${namespace}`)
}
fastify.elastic[namespace] = client
fastify.addHook('onClose', async (instance) => {
// v8 client.close returns a promise and does not accept a callback
await instance.elastic[namespace].close()
})
} else {
fastify
.decorate('elastic', client)
.addHook('onClose', async (instance) => {
await instance.elastic.close()
})
}
}
module.exports = fp(fastifyElasticsearch, {
fastify: '5.x',
name: '@fastify/elasticsearch'
})
module.exports.default = fastifyElasticsearch
module.exports.fastifyElasticsearch = fastifyElasticsearch
module.exports.isElasticsearchClient = isElasticsearchClient