node.js - 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));
};
解决方案
推荐阅读
- python-3.x - 在 python 中覆盖 init()。TypeError: __init__() 接受 1 个位置参数,但给出了 3 个
- javascript - 如何将 javascript 对象作为 URL 传递给 django 服务器
- java - Apache POI Excel 仅显示数据标签和切割图
- javascript - 显示多个网站的最佳做法
- javascript - 如何在 React 中正确地自动完成
- typo3 - TYPO3 8.7/9.5 pibase $_POST 不可用?
- reactjs - React Native 无法使用来自 AsyncStorage 的数据更新 State Hook
- c++ - 如何OPENCV+CUDA+VideoCapture?
- java - 在 gradle 中加载依赖项
- c++ - 如何安全地停止 IOCP WSARecv() 任务并释放 WSAOVERLAPPED 结构?