首页 > 解决方案 > Fastify 调用多个 preHandler 钩子时多次调用控制器方法

问题描述

我有一个带有以下模式的 fastify 路由方法。

fastify.post('/club', createClubSchema, createClub(fastify));

const createClubSchema = {
    schema: {
        tags: ['club'],
        security: [
            {
                ApiKeyAuth: [],
            },
        ],
        body: {
            type: 'object',
            required: ['name', 'description'],
            properties: {
                name: { type: 'string', minLength: 3 },
                description: { type: 'string', minLength: 3 },
                logoUrl: { type: 'string', minLength: 3 },
            },
        },
        response: {
            200: {
                type: 'object',
                properties: {
                    status: { type: 'string' },
                    data: {
                        type: 'object',
                        properties: {
                            name: { type: 'string' },
                            description: { type: 'string' },
                            id: { type: 'number' },
                            color: { type: 'string' },
                            logoUrl: { type: 'string' },
                            createdAt: { type: 'string' },
                            updatedAt: { type: 'string' },
                        },
                    },
                },
            },
        },
    },
    preHandler: [grantAccess('create', 'club')],
};

现在这条路由位于文件夹中,该文件夹autohooks.js有一个自己的预处理程序钩子,用于检查请求中是否包含用于身份验证的令牌。

问题是在调用控制器方法preHandler的区域上都调用了钩子之后createClub,所以总共2次。

问题是什么?我该如何解决这个问题?

编辑

这是autoHooks.js文件 const authentication = require('../../middlewares/authentication');

module.exports = async function (fastify, opts, next) {
    fastify.addHook('preHandler', authentication.authenticate(fastify));
};

标签: node.jsfastify

解决方案


推荐阅读