繁体   English   中英

如何获取 sequelize 查询之外的数据?

[英]How do i get the data outside the sequelize query?

在后端,我有一个控制器,它从前端接收登录数据(用户名和密码),验证它们,然后将结果响应返回给前端。 这是控制器:

/* POST /api/login */
exports.Login = (req, res, next) => {
  const incomingUsername = req.body.username;
  const incomingPassword = req.body.password;

  const result = validation.ValidateLoginData(
    incomingUsername,
    incomingPassword
  );

  /* Validation fails when the validationResult === 0 */
  /* Validation succeeds when the validationResult === 1 */
  if (result.validationResult === 0) {
    res.json({ result: 0, message: result.validationMessage });
  } else if (result.validationResult === 1) {
    res.json({ result: 1, message: result.validationMessage });
  }
};

ValidateLoginData()函数包含以下步骤:

  1. 检查用户名或密码是否不存在(未定义)
  2. 检查用户名或密码是否为空字符串
  3. 检查用户是否是所有者(特殊情况)
  4. 检查用户是否存在于数据库中
  5. 检查密码是否正确

我想在ValidateLoginData()函数中保留所有验证逻辑。

这是第一个场景:

exports.ValidateLoginData = (incomingUsername, incomingPassword) => {
  /* Check if the username or password does not exist (undefined) */
  /* Check if the username or password is empty string */
  /* Check if the user is owner (Special case) */
  if (incomingUsername === undefined || incomingPassword === undefined) {
    return {
      validationResult: 0,
      validationMessage: "Undefined username or password!",
    };
  } else if (incomingUsername === "" || incomingPassword === "") {
    return {
      validationResult: 0,
      validationMessage: "Empty username or password!",
    };
  } else if (
    incomingUsername === process.env.OWNER_USERNAME &&
    incomingPassword === process.env.OWNER_PASSWORD
  ) {
    return {
      validationResult: 1,
      validationMessage:
        process.env.OWNER_USERNAME + " (Owner) Logged in sucessfully!",
    };
  }

  /* Here is want to return the result of the database query and it should be the
  user data for further validation like this */
  const user = User.findOne({
    where: {
      username: incomingUsername,
    },
  });

  if (user === null) {
    return {
      validationResult: 0,
      validationMessage: "Incorrect username!",
    };
  } else if (user.dataValues.username === incomingUsername) {
    if (user.dataValues.password === incomingPassword) {
      return {
        validationResult: 1,
        validationMessage: "You logged in successfully!",
      };
    }
  }
};

第二种情况:

/* Or if i can place the validation inside the then() and then return
the validation result out of the ValidateLoginData function */
User.findOne({
    where: {
      username: incomingUsername,
    },
  }).then((user) => {
    if (user === null) {
      return {
        validationResult: 0,
        validationMessage: "Incorrect username!",
      };
    } else if (user.dataValues.username === incomingUsername) {
      if (user.dataValues.password === incomingPassword) {
        return {
          validationResult: 1,
          validationMessage: "You logged in successfully!",
        };
      }
    }
  });

第三个场景:

/* Or if i can place the validation for password inside the second
then() i do not want to have nesting as it makes the code
more complicated */
  User.findOne({
    where: {
      username: incomingUsername,
    },
  })
    .then((user) => {
      if (user === null) {
        /* This returns the result outside the ValidateLoginData function */
        return {
          validationResult: 0,
          validationMessage: "Incorrect username!",
        };
      } else if (user.dataValues.username === incomingUsername) {
        /* This returns the user data to the next then() not outside the
        ValidateLoginData function */
        return user;
      }
    })
    .then((user) => {
      if (user.dataValues.password !== incomingPassword) {
        return {
          validationResult: 0,
          validationMessage: "Incorrect Password",
        };
      } else if (user.dataValues.password === incomingPassword) {
        return {
          validationResult: 1,
          validationMessage: "You logged in successfully!",
        };
      }
    });

这样做的目标是我想:

  1. 将所有验证逻辑放在控制器外部和validateLoginData函数中。
  2. 从包含validationResultvalidationMessagevalidateLoginData函数返回一个对象。
  3. 尽量避免嵌套。

sequelize 返回一个promise,因此变量databaseResult 在.then() 中的赋值之前打印在console.log 中

试试这个:

let databaseResult = null;
  User.findOne({
    where: {
      username: incomingUsername,
    },
  })
    .then((res) => {
      databaseResult = res;
      console.log(databaseResult);
    })
    .catch((err) => {
      console.log(err);
    });

如果你想确保 sequelize 中的操作出现,你的其余代码应该在 .then() 中,否则你可以像这样使用 async await :

async function myFunct() {
try {
  let databaseResult = await User.findOne({
    where: {
      username: incomingUsername,
    },
  })
} catch(err) {
console.log(err);
}
console.log(databaseResult);
}

顺便说一句,在函数中使用 async 可能很棘手,因为该函数将返回一个承诺:P

我是这样制作的:

/* POST /api/login */
exports.Login = async (req, res, next) => {
  const incomingUsername = req.body.username;
  const incomingPassword = req.body.password;

  const result = await validation.ValidateLoginData(
    incomingUsername,
    incomingPassword
  );

  /* Validation fails when the validationResult === 0 */
  /* Validation succeeds when the validationResult === 1 */
  if (result.validationResult === 0) {
    res.json({ result: 0, message: result.validationMessage });
  } else if (result.validationResult === 1) {
    res.json({ result: 1, message: result.validationMessage });
  }
};
const User = require("../models/UserModel.js");

exports.ValidateLoginData = async (incomingUsername, incomingPassword) => {
  /* Check if the username or password does not exist (undefined) */
  /* Check if the username or password is empty string */
  /* Check if the user is owner (Special case) */
  if (incomingUsername === undefined || incomingPassword === undefined) {
    return {
      validationResult: 0,
      validationMessage: "Undefined username or password!",
    };
  } else if (incomingUsername === "" || incomingPassword === "") {
    return {
      validationResult: 0,
      validationMessage: "Empty username or password!",
    };
  } else if (
    incomingUsername === process.env.OWNER_USERNAME &&
    incomingPassword === process.env.OWNER_PASSWORD
  ) {
    return {
      validationResult: 1,
      validationMessage:
        process.env.OWNER_USERNAME + " (Owner) Logged in sucessfully!",
    };
  }

  /* Get user from database */
  const user = await User.findOne({
    where: {
      username: incomingUsername,
    },
  });

  /* Validate username and password */
  if (user === null) {
    return {
      validationResult: 0,
      validationMessage: "Wrong username!",
    };
  } else if (user.getDataValue("username") === incomingUsername) {
    if (user.getDataValue("password") !== incomingPassword) {
      return {
        validationResult: 0,
        validationMessage: "Wrong Password!",
      };
    } else if (user.getDataValue("password") === incomingPassword) {
      return {
        validationResult: 1,
        validationMessage: incomingUsername + " logged in successfully!",
      };
    }
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM