首页 > 解决方案 > 如何以更优雅的方式验证这一点?

问题描述

我试图在我的项目中做登录/注册模块。这是我的登录功能。我希望有一个函数可以为我验证所有事情,这样我就不必使用这么多“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);
  }
};

标签: javascriptnode.jsmongodbpure-function

解决方案


将我的评论抽象为答案。

关于纯函数:

如果我正确理解纯函数,我认为您不能拥有调用可能失败的外部 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.`,
  });
}

推荐阅读