我想将
token: string
字段添加到 FastifyContext 接口。为此,我创建了以下文件结构:
projectDir
|__src
| |__@types
| | |__fastify
| | | |__index.d.ts
| |__api
| | |__authHook.ts
|__tsconfig.json
src/@types/fatify/index.d.ts
的内容:
declare module 'fastify' {
export interface FastifyContext<ContextConfig>{
token: string
}
}
内容
src/api/authHook.ts
import {FastifyRequest, FastifyReply} from "fastify";
export default async function authHook(request: FastifyRequest, reply: FastifyReply): Promise<void>{
// Some logic
const token = "example_token" // some result from logic
request.context.token = token;
}
tsconfig.json
的内容:
{
"compilerOptions": {
...
"typeRoots": ["src/@types"],
...
}
}
但是当我运行代码时出现以下错误:
Property 'token' does not exist on type 'FastifyContext<unknown>'.
我做错了什么?
request.context
已弃用
import { onRequestHookHandler } from "fastify";
declare module "fastify" {
export interface FastifyContextConfig {
token: string;
}
}
const authHook: onRequestHookHandler = async function (request, reply) {
const token = "example_token";
request.routeOptions.config.token = token;
};
export default authHook;