我正在尝试使用TypeORM制作GraphQL(GraphQL Yoga)api,并且在如何检查每个请求以验证JWT令牌并将其插入请求对象中遇到问题。
我的代码如下:
index.ts :
const app = new GraphQLServer({
schema: mergeSchemas({ schemas }),
context: ({ req }) => ({
req,
}),
});
app.express.post('/', addUser);
addUser.ts :
import { Request, Response, NextFunction } from 'express';
import * as jwt from 'jsonwebtoken';
import { refreshTokens } from '../utils/auth';
const addUser = async (req: Request, res: Response, next: NextFunction) => {
const SECRET = process.env.SECRET;
const REFRESH_SECRET = process.env.REFRESH_SECRET;
const token = req.headers['x-token'];
if (token) {
try {
if (SECRET) {
const id = jwt.verify(token[0], SECRET);
req.user = id;
}
} catch (e) {
const refreshToken = req.headers['x-refresh-token'];
if (refreshToken && SECRET && REFRESH_SECRET) {
const newTokens = await refreshTokens(refreshToken[0], SECRET, REFRESH_SECRET);
if (newTokens.token && newTokens.refreshToken) {
res.set('Access-Control-Expose-Headers', 'x-token, x-refresh-token');
res.set('x-token', newTokens.token);
res.set('x-refresh-token', newTokens.refreshToken);
}
req.user = newTokens.user;
}
}
}
next();
}
export default addUser;
我已经通过接口扩展了Request对象(不确定是否正确加载了该对象)。
express.d.ts :
declare namespace Express {
export interface Request {
user: any
}
}
还有我的 tsconfig.json :
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": [
"dom",
"es6",
"es2017",
"esnext.asynciterable"
],
"sourceMap": true,
"outDir": "./dist",
"moduleResolution": "node",
"removeComments": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"exclude": [
"node_modules"
],
"include": [
"./src/**/*.tsx",
"./src/**/*.ts"
]
}
但是当我尝试启动服务器时,出现以下错误:
TSError: ⨯ Unable to compile TypeScript:
src/middleware/addUser.ts(14,13): error TS2339: Property 'user' does not exist on type 'Request'.
src/middleware/addUser.ts(25,13): error TS2339: Property 'user' does not exist on type 'Request'.
有人解决了这个问题,或者对如何改进此代码有任何想法吗?
谢谢!