Skip to content

Understand how to use Fastify plugin #1056

Closed
@SkyTik

Description

@SkyTik

What are you trying to achieve, or the steps to reproduce?

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 searched on Google but still can not find any satisfactory answer.
Many thanks

Context

  • node version: 20.14.0
  • fastify version: 4.28.1
  • os: Mac

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions