最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - TypeScript Error: 'authenticate' Property Does Not Exist on FastifyInstance Type When Using JWT - Stac

programmeradmin0浏览0评论

I'm having an issue with my Fastify + TypeScript application. When I try to use the authenticate method in my routes, TypeScript gives me the following error:

Property 'authenticate' does not exist on type 'FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProviderDefault>'.

This is the code that's causing the problem:

import { FastifyInstance, FastifyPluginOptions } from "fastify";
import { UserController } from "../controllers/UserController";

const userRoutes = async (
  fastify: FastifyInstance,
  options: FastifyPluginOptions
) => {
  fastify.addHook("preHandler", fastify.authenticate);

  fastify.get("/", UserController.getUsers);
  fastify.get("/:id", UserController.getUserById);
  fastify.get("/mail/:mail", UserController.getUserByMail);
  fastify.get("/user/:user", UserController.getUserByUser);
};

export default userRoutes;

I've already tried:

  1. Decorating the Fastify instance with the authenticate method in my main file:
import fastify, { FastifyReply, FastifyRequest } from "fastify";
import { connectDB } from "./config/db";
import userRoutes from "./routes/userRoutes";
import projectsRoutes from "./routes/projectRoutes";
import fastifyJwt from "@fastify/jwt";

const app = fastify({ logger: true });

app.register(fastifyJwt, {
  secret: process.env.SECRET_KEY || "secret_key",
});

app.decorate("authenticate", async function (request, reply) {
  try {
    await request.jwtVerify();
  } catch (err) {
    reply.send(err);
  }
});

app.register(userRoutes, { prefix: "/api/v1/user" });
app.register(projectsRoutes, { prefix: "/api/v1/project" });

connectDB();
export default app;
  1. Creating a type definition file in src/types/fastify.d.ts:
import "fastify";

declare module "fastify" {
  export interface FastifyInstance {
    authenticate: any;
  }
}
  1. My tsconfig.json configuration:
{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./src/types"],
    "outDir": "./dist",
    "rootDir": "./src",
    "lib": ["esnext"],
    "target": "ESNext",
    "moduleResolution": "NodeNext",
    "module": "NodeNext",
    "strict": false,
    "sourceMap": true,
    "esModuleInterop": true,
    "declaration": true
  },
  "include": ["src/**/*.ts"]
}

Full error output:

/home/user/project/node_modules/ts-node/src/index.ts:859
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/routes/userRoutes.ts:8:41 - error TS2339: Property 'authenticate' does not exist on type 'FastifyInstance<...>'.

8   fastify.addHook("preHandler", fastify.authenticate);
                                          ~~~~~~~~~~~~

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论