fastify-min/plugins/redis.js
2024-11-09 08:10:29 -06:00

27 lines
731 B
JavaScript

import fp from 'fastify-plugin';
import Redis from 'ioredis';
// Fastify plugin for ioredis
async function redisPlugin(fastify) {
const redis = new Redis({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
});
console.log(`Attempting to connect to redis@${process.env.REDIS_HOST}:${process.env.REDIS_PORT} ...`)
redis.on('connect', () => {
console.log(`Connection success to Redis at: ${new Date().toISOString()}`);
});
// Attach redis client to Fastify instance
fastify.decorate('redis', redis);
// Close redis connection on server shutdown
fastify.addHook('onClose', (app, done) => {
app.redis.quit();
done();
});
}
// Export as a fastify plugin
export default fp(redisPlugin);