gpt4 book ai didi

node.js - 如何将类验证器实现为中间件?

转载 作者:行者123 更新时间:2023-12-05 04:52:59 24 4
gpt4 key购买 nike

我一直在尝试使用 class-validator 作为中间件来验证我的一些数据。

我很想得到一些关于

的建议

how can I also validate updates and what's a good validation

这是当前类验证器,用于验证尝试注册时发送的 req.body

export default async (req: Request, res: Response, next: NextFunction) => {
let user = new User();
user.username = req.body.username;
user.email = req.body.email;
user.password = req.body.password;
let fieldErrors = await validate(user);
if (fieldErrors.length > 0) {
let errors = ValidatorErrToFieldErr(fieldErrors);
next(new HttpExeception({ statusCode: httpCode.BAD_REQUEST, errors }));
} else {
next();
}
};

什么是好的验证模式?我 Controller 处理一些逻辑,这些逻辑又调用服务来改变数据库。

AuthController.ts

public static Register = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
req.body.password = await argon2.hash(req.body.password);
let modelUser = await service.addUser(req.body);
let user: IUserMe = {
//reasign user fields
};
req.session.user = {
id: user.id,
username: user.username,
isAdmin: user.isAdmin,
};

res.json({ user });
} catch (error) {
if (error.code === "23505") {
next(
new HttpExeception({
statusCode: httpCode.BAD_REQUEST,
errors: duplicationErrToFieldError(error.detail),
})
);
} else next(new HttpExeception({ statusCode: httpCode.SERVER_ERROR }));
}
};

用户服务.ts

async addUser(input: IRegisterInput): Promise<User> {
return await getRepository(User).save(input);
}

最佳答案

所以大多数中间件都是在路由内部调用的。我将使用 Express、Passport 和 TypeScript 的示例,因为这是我最了解的。

假设我不希望用户在未登录的情况下访问我的“/home”页面。所以我编写了一个中间件函数:

export default ( req: Request, res: Response, next: NextFunction): void => {
if(req.user != undefined){
next();
}
else{
res.status(401);
}
}

这类似于您的 class-validator 函数。现在,我们需要确保此函数在对“/home”进行任何 API 调用之前运行。

因此,我们将api路由写成

import * as express from “express”;
import {Request, Response} from “express”;
import isAuthenticated from “isAuthenticated.ts”;

class HomeRouter{
public path = “/”;
public router = App.router();

constructor(){
this.initRoutes();
}

public initRoutes(){
this.router.get(“/home”, isAuthenticated, (req: Request, res: Response) => {
res.send(“/index.html”);
}
}
}

这将强制 isAuthenticated 在执行其余路由中的任何逻辑之前运行。如果您希望中间件应用于对服务器的每次调用,只需将 express.use(isAuthenticated); 放入您的 server.ts 文件中。如果您使用的是我未能识别的与 Express 不同的技术,我确信前提是相同的,并且在文档中将如何使用。

关于node.js - 如何将类验证器实现为中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66299222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com