-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (42 loc) · 1.5 KB
/
index.js
File metadata and controls
55 lines (42 loc) · 1.5 KB
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
'use strict'
const fp = require('fastify-plugin')
const { GlideClient } = require('@valkey/valkey-glide')
async function fastifyValkey (fastify, options) {
const { namespace, closeClient = false, ...valkeyOptions } = options
let client = options.client || null
if (namespace) {
if (!fastify.valkey) {
fastify.decorate('valkey', Object.create(null))
}
if (fastify.valkey[namespace]) {
throw new Error(`Valkey '${namespace}' instance namespace has already been registered`)
}
const closeNamedInstance = (fastify) => { fastify.valkey[namespace].close() }
client = await setupClient(fastify, client, closeClient, valkeyOptions, closeNamedInstance)
fastify.valkey[namespace] = client
} else {
if (fastify.valkey) {
throw new Error('@fastify/valkey has already been registered')
}
const close = (fastify) => { fastify.valkey.close() }
client = await setupClient(fastify, client, closeClient, valkeyOptions, close)
fastify.decorate('valkey', client)
}
}
async function setupClient (fastify, client, closeClient, valkeyOptions, closeInstance) {
if (client) {
if (closeClient === true) {
fastify.addHook('onClose', closeInstance)
}
} else {
client = await GlideClient.createClient(valkeyOptions)
fastify.addHook('onClose', closeInstance)
}
return client
}
module.exports = fp(fastifyValkey, {
fastify: '5.x',
name: '@fastify/valkey-glide'
})
module.exports.default = fastifyValkey
module.exports.fastifyValkey = fastifyValkey