diff --git a/src/plugins/redis.ts b/src/plugins/redis.ts new file mode 100644 index 0000000..3760029 --- /dev/null +++ b/src/plugins/redis.ts @@ -0,0 +1,32 @@ +import { FastifyInstance, FastifyPluginAsync } from 'fastify'; +import { Redis } from 'ioredis'; +import fp from 'fastify-plugin'; +import { env } from '../config/env.js'; + +declare module 'fastify' { + interface FastifyInstance { + redis: Redis; + } +} + +const redisPlugin: FastifyPluginAsync = async (app: FastifyInstance) => { + const redis = new Redis(env.REDIS_URL, { + maxRetriesPerRequest: 3, + retryStrategy(times: number) { + const delay = Math.min(times * 100, 3000); + return delay; + }, + }); + + redis.on('error', (err: Error) => { + app.log.error({ err }, 'Redis connection error'); + }); + + app.decorate('redis', redis); + + app.addHook('onClose', async () => { + await redis.quit(); + }); +}; + +export default fp(redisPlugin, { name: 'redis' });