I’m studying Fastify and register plugin with @fastify/redis like this
app.register(redisPlugin, {
client: initRedis(app.config.REDIS_INTERNAL__HOST, app.config.REDIS_INTERNAL__PASS),
closeClient: true,
});
And register route:
import { FastifyInstance, FastifyPluginAsync } from "fastify";
import v1Routes from "./v1/index.js";
const routes: FastifyPluginAsync = async (fastify: FastifyInstance): Promise<void> => {
fastify.register(v1Routes, { prefix: "/v1" });
};
export default routes;
and inside v1 route
const v1Routes: FastifyPluginAsync = async (fastify: FastifyInstance): Promise<void> => {
fastify.register(seedlogsRoutes, { prefix: "/seedlogs" });
};
route with controller
const orderRoutes: FastifyPluginAsync = async (fastify: FastifyInstance) => {
fastify.get("/", getOrders);
};
export default orderRoutes;
with getOrders function, I can access redis like this:
const getOrders = async (request: FastifyRequest, reply: FastifyReply) => {
const redis = request.server.redis;
await redis.set("orders", "abc");
const orders = await redis.get("orders");
return { message: "Orders", orders };
};
But what if I want to access redis from an inner service, how can I access redis from the
FastifyInstance, like
const cacheOrder = async (order) => {
await redis.set("order",order)
}
Should I init a client before passing it to the plugin and reuse it wherever does not have access to the FastifyInstance?
import redis from "./cache/redis.js"
I try to search on Google but still can not find any satisfactory answer. Any comment is appreciated. Many thanks.
2
Answers
No, or you will have global clients that is a foot-gun. You need to propagate the redis client attached to the Fastify server.
This code can be simplified:
Be sure to have the right
server
instance, that is bound tothis
almost everywhere in:Documentation reference: https://fastify.dev/docs/latest/Reference/Routes/#routes-options
Useful reading: https://backend.cafe/the-complete-guide-to-the-fastify-plugin-system
With Decorators, you can access it from anywhere within the Fastify context, including routes, hooks, and services.
Then, in your service or other parts of your application, you can access it using fastify.redis:
When calling this function, pass the Fastify instance:
This will work.