我要翻译的内容: 如何编写编辑控制器

huangapple go评论92阅读模式
英文:

How can I write an edit controller

问题

以下是您要求翻译的内容:

  1. 我有一个Node.js后端和一个控制器来添加特定功能有一个添加功能但没有更新功能我该如何编写一个更新功能我对后端不熟悉但被分配了这个任务
  2. 以下是该功能的添加功能我该如何编写一个类似于更新的函数
  3. async addRole(req, res, next) {
  4. let body = req.body;
  5. const model = new entityRoles(body);
  6. try {
  7. const alreadyExist = await entityRoles.getByName(req.body.name);
  8. if (!alreadyExist) {
  9. const saveResponse = await model.save()
  10. return res.status(httpStatus.OK).json(new APIResponse(saveResponse, 'Entity role created successfully.', httpStatus.OK));
  11. } else if (alreadyExist.roleName === req.body.roleName) {
  12. res
  13. .status(httpStatus.OK)
  14. .send({ message: "name is already exist" });
  15. } else {
  16. res
  17. .status(httpStatus.OK)
  18. .send({ message: "Error Adding entity role" });
  19. }
  20. } catch (e) {
  21. if (e.code === 11000) {
  22. return res
  23. .status(httpStatus.OK)
  24. .send({ message: "entity role is already exist with this name" });
  25. } else {
  26. return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(new APIResponse({}, 'Error adding entity role', httpStatus.INTERNAL_SERVER_ERROR, e));
  27. }
  28. }
  29. }
  30. EDIT使用的框架是express.jsODMmongoose数据库是mongodb

请注意,我已经忽略了您提到的代码部分,只返回了翻译好的文本。

英文:

I have a nodeJS backend and a controller to add a specific function. There's an add function but there's no update function. how can I write an update function. I'm not good with backend and I have been tasked with this.

Below is the add function for the feature. How do I write a function like that for update:

  1. async addRole(req, res, next) {
  2. let body = req.body;
  3. const model = new entityRoles(body);
  4. try {
  5. const alreadyExist = await entityRoles.getByName(req.body.name);
  6. if (!alreadyExist) {
  7. const saveResponse = await model.save()
  8. return res.status(httpStatus.OK).json(new APIResponse(saveResponse, 'Entity role created successfully.', httpStatus.OK));
  9. } else if (alreadyExist.roleName === req.body.roleName) {
  10. res
  11. .status(httpStatus.OK)
  12. .send({ message: "name is already exist" });
  13. } else {
  14. res
  15. .status(httpStatus.OK)
  16. .send({ message: "Error Adding entity role" });
  17. }
  18. } catch (e) {
  19. if (e.code === 11000) {
  20. return res
  21. .status(httpStatus.OK)
  22. .send({ message: "entity role is already exist with this name" });
  23. } else {
  24. return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(new APIResponse({}, 'Error adding entity role', httpStatus.INTERNAL_SERVER_ERROR, e));
  25. }
  26. }

EDIT: the framework used is express.js, ODM is mongoose and the database is mongodb

答案1

得分: 0

以下是代码的翻译部分:

  1. async function updateRole(req, res, next) {
  2. /**
  3. * 构造请求体
  4. * @example
  5. * {
  6. * id: 1, // 角色的ID
  7. * name: 'admin' // 新的角色名称
  8. * }
  9. */
  10. const body = req.body;
  11. try {
  12. const model = await entityRoles.findById(req.body.id);
  13. /**
  14. * 检查数据库中是否存在模型
  15. */
  16. if (!model) {
  17. return res.status(httpStatus.OK).send({ message: '未找到ID对应的角色' });
  18. }
  19. /**
  20. * 检查数据库中是否存在具有相同名称的新角色
  21. *
  22. * `body.name !== model.name` 这个语句确保检查角色是否正确
  23. * 因为在前面的语句中,总是会有一个具有旧名称的角色从数据库中获取。
  24. */
  25. if (body.name !== model.name && (await entityRoles.getByName(body.name))) {
  26. return res.status(httpStatus.OK).send({ message: '名称已存在' });
  27. }
  28. /**
  29. * 在这里添加更多的业务逻辑,例如检查其他字段或名称是否正确
  30. */
  31. /**
  32. * 最后,使用新数据更新模型并保存到数据库。
  33. */
  34. model.name = body.name;
  35. /**
  36. * 更新角色的其余部分
  37. * @example
  38. * model.lastUpdatedAt = Date.now();
  39. */
  40. const saveResponse = await model.save();
  41. return res.status(httpStatus.OK).json(new APIResponse(saveResponse, '实体角色更新成功。', httpStatus.OK));
  42. } catch (e) {
  43. /**
  44. * 检查错误的 `code` 来返回给客户端
  45. */
  46. if (e.code === 11000) {
  47. return res.status(httpStatus.OK).send({ message: '角色名称已存在,请更新为其他名称。' });
  48. } else {
  49. return res
  50. .status(httpStatus.INTERNAL_SERVER_ERROR)
  51. .json(new APIResponse({}, '添加实体角色时出错', httpStatus.INTERNAL_SERVER_ERROR, e));
  52. }
  53. }
  54. }

请注意,我只翻译了代码部分,不包括问题中的其他内容。

英文:

Your question isn't clear such as: framework, orm library, database. But this below code is sample that you can reference:

  1. async function updateRole(req, res, next) {
  2. /**
  3. * Structure body
  4. * @example
  5. * {
  6. * id: 1, // id of role
  7. * name: 'admin' // new name of role
  8. * }
  9. */
  10. const body = req.body;
  11. try {
  12. const model = await entityRoles.findById(req.body.id);
  13. /**
  14. * Check have model exist on database
  15. */
  16. if (!model) {
  17. return res.status(httpStatus.OK).send({ message: 'not found role by id' });
  18. }
  19. /**
  20. * Check new name of role is existed in database
  21. *
  22. * `body.name !== model.name` this statement make sure check role is correctly
  23. * because always exist one role with old name that get from database in previous statement.
  24. */
  25. if (body.name !== model.name && (await entityRoles.getByName(body.name))) {
  26. return res.status(httpStatus.OK).send({ message: 'name is already exist' });
  27. }
  28. /**
  29. * Add more your business logic at here such as check other filed or name is correctly
  30. */
  31. /**
  32. * Finally, model will be updated with new data and save to database.
  33. */
  34. model.name = body.name;
  35. /**
  36. * Update rest of role
  37. * @example
  38. * model.lastUpdatedAt = Date.now();
  39. */
  40. const saveResponse = await model.save();
  41. return res.status(httpStatus.OK).json(new APIResponse(saveResponse, 'Entity role updated successfully.', httpStatus.OK));
  42. } catch (e) {
  43. /**
  44. * Check `code` of error to return client
  45. */
  46. if (e.code === 11000) {
  47. return res.status(httpStatus.OK).send({ message: 'name of role is existed. please update a other name.' });
  48. } else {
  49. return res
  50. .status(httpStatus.INTERNAL_SERVER_ERROR)
  51. .json(new APIResponse({}, 'Error adding entity role', httpStatus.INTERNAL_SERVER_ERROR, e));
  52. }
  53. }
  54. }

答案2

得分: 0

  1. async updateRole(req, res, next) {
  2. try {
  3. const roleId = req.params.id; // 从请求参数中提取角色ID
  4. const updatedRoleData = req.body; // 从请求体中提取更新后的角色信息
  5. const existingRole = await entityRoles.findById(roleId);
  6. if (!existingRole) {
  7. return res.status(httpStatus.NOT_FOUND).send({ message: "未找到角色。" });
  8. }
  9. // 使用更新后的角色信息更新现有角色
  10. existingRole.name = updatedRoleData.name;
  11. existingRole.description = updatedRoleData.description;
  12. // 根据需要更新其他属性
  13. const updatedRole = await existingRole.save();
  14. return res.status(httpStatus.OK).json(new APIResponse(updatedRole, '角色更新成功。', httpStatus.OK));
  15. } catch (error) {
  16. return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(new APIResponse({}, '更新角色时发生错误。', httpStatus.INTERNAL_SERVER_ERROR, error));
  17. }
  18. }
英文:
  1. async updateRole(req, res, next) {
  2. try {
  3. const roleId = req.params.id; // Extract the role ID from the request parameters
  4. const updatedRoleData = req.body; // Extract the updated role information from the reque`enter code here`st body
  5. const existingRole = await entityRoles.findById(roleId);
  6. if (!existingRole) {
  7. return res.status(httpStatus.NOT_FOUND).send({ message: "Role not found." });
  8. }
  9. // Update the existing role with the updated role information
  10. existingRole.name = updatedRoleData.name;
  11. existingRole.description = updatedRoleData.description;
  12. // Update other properties as needed
  13. const updatedRole = await existingRole.save();
  14. return res.status(httpStatus.OK).json(new APIResponse(updatedRole, 'Role updated successfully.', httpStatus.OK));
  15. } catch (error) {
  16. return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(new APIResponse({}, 'Error updating role.', httpStatus.INTERNAL_SERVER_ERROR, error));
  17. }
  18. }

huangapple
  • 本文由 发表于 2023年7月4日 22:54:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定