如何解决我怎样才能更优雅地验证这一点? 关于纯函数:重复时:
我正在尝试在我的项目中执行登录/注册模块。这是我的登录功能。我想拥有一个可以为我验证所有内容的函数,因此我不必使用太多的“ if”语句。我试图使用纯函数,但是完全不知道该怎么做。有人可以帮我吗?
const loginUser = async (req,res,next) => {
const { password,email } = req.body;
if (!email) {
return res.status(400).json({
message: "Error: Email cannot be blank.",});
}
if (!password) {
return res.status(400).json({
message: "Error: Password cannot be blank.",});
}
try {
const user = await User.findOne({ email: email });
if (!user)
return res.status(400).json({
message: "Invalid user",});
if (!validPassword(password,user.password))
return res.status(400).json({
message: "Invalid password",});
const { name,likedArr,_id } = user;
const token = crypto.randomBytes(32).toString("hex");
const userSession = new UserSession({ userId: _id,token });
await userSession.save();
return res.status(200).json({
message: "Valid login",token: token,user: {
name,userId: _id,},});
} catch (err) {
next(err);
}
};
解决方法
将我的评论抽象为答案。
关于纯函数:
如果我正确地理解了纯函数,我认为您不能使用一个纯函数来调用可能失败的外部API,因为相同的输入可能会根据API的外部状态返回不同的结果(除非API本身可以通过某种方式得到保证)。 (Definition of a pure function)
重复时:
我真的认为您在这里没有很多重复。您的代码很清晰,只有4个条件,所有条件都需要测试。您可以根据条件将JSON返回的相似性抽象为类似模板字符串的内容,但是我认为可以为您的代码添加混乱和不透明性,如果这不是很好的折衷方案你做得太多了。
如果您想举一个例子说明我的意思:
if (!email) {
return res.status(400).json({
message: "Error: Email cannot be blank.",});
}
if (!password) {
return res.status(400).json({
message: "Error: Password cannot be blank.",});
}
可以成为...
if (!email || !password) {
return res.status(400).json({
message: `Error: ${!email ? 'Email' : 'Password'} cannot be blank.`,});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。