javascript - 如何以更优雅的方式验证这一点?
问题描述
我试图在我的项目中做登录/注册模块。这是我的登录功能。我希望有一个函数可以为我验证所有事情,这样我就不必使用这么多“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,
likedArr,
userId: _id,
},
});
} catch (err) {
next(err);
}
};
解决方案
将我的评论抽象为答案。
关于纯函数:
如果我正确理解纯函数,我认为您不能拥有调用可能失败的外部 API 的纯函数,因为相同的输入可能会根据 API 的外部状态返回不同的结果(除非该 API 得到保证以某种方式净化自己)。(纯函数的定义)
关于重复:
我真的认为你在这里没有太多重复。您的代码很清晰,只有 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.`,
});
}
推荐阅读
- android - 独立世博会(ExpoKit)推送通知
- python - 当单击而不是外壳时,如何使按钮的值显示到 tkinter 上?
- python - 如何使用 Atom 编辑器将脚本的路径设置为 Python 中的工作目录?
- scala - 如何使用 joinWith 加入 2 个以上的数据集?
- angular - Angular 7 不发送 HttpClient POST 请求 - 而是死于“未知错误”
- angular - 如何将 aws amplify 添加到现有的 Angular 项目中
- php - 如何将 PHP 文件连接到 GitHub 页面(不同的存储库)?
- swift - 如何避免在返回对象的辅助函数中进行不必要的初始化?
- reactjs - LocalStorage 无法正常工作 ReactJS
- django - 未找到“索引”的反向。'index' 不是有效的视图函数或模式名称。PasswordChangeView 和 PasswordChangeForm