使用 Fastify preHandler 中间件

Using Fastify preHandler middleware

在访问此路由之前通过中间件对用户进行身份验证。

当我将 tokenController.authUser 作为中间件传递时 tokenServicetokenController 中是 undefined。但是,当我 运行 此方法作为路由内部的函数而不是中间件时,它工作正常。

server.post('/api/admin/test', { preHandler: [tokenController.authUser] }, async (request: any, reply: any) => {
    return null
});

令牌控制器:-

import { Users } from "@prisma/client";
import ITokenService from "../../services/tokenService/ITokenService";
import ITokenController from "./ITokenController";

export default class TokenController implements ITokenController {
    private readonly tokenService: ITokenService;
    constructor(_tokenService: ITokenService) {
        this.tokenService = _tokenService;
    }

    async authUser(request: any, reply: any): Promise<Users | Error> {
        const authHeader = request.headers['authorization'];
        const token = authHeader && authHeader.split(' ')[1];
        if (token === null)
            return reply.code(401);
        try {
            const result = await this.tokenService.verifyToken(token);
            console.log(result);
            return result;
        }
        catch (e) {
            reply.code(401);
            return new Error("Error");
        }
    }
}

令牌服务:-

import { Users } from "@prisma/client";
import ITokenService from "./ITokenService";

export default class TokenService implements ITokenService {
    private readonly sign: Function;
    private readonly verify: Function;
    private readonly secretKey: string;
    constructor(sign: Function, verify: Function, _secretKey: string) {
        this.sign = sign;
        this.verify = verify;
        this.secretKey = _secretKey;
    }

    public async generateToken(user: Users): Promise<string> {
        return await this.sign({ user }, this.secretKey);
    }

    public async verifyToken(token: string): Promise<Users | Error> {
        const result = await this.verify(token, this.secretKey);
        return result;
    }
}

出于某种原因,制作一个单独的中间件函数并在该方法中调用 tokenController.authUser 工作正常。

const middleware = (_req, _res, next) => {
  console.log('middleware');
  next()
}


server.post('/api/admin/test', { preHandler: [middleware] }, async (request: any, reply: any) => {
    return null
});