crud.mock.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * @Author: helin3
  3. * @Date: 2024-03-25 13:47:19
  4. * @LastEditors: helin3
  5. * @LastEditTime: 2024-03-25 16:16:18
  6. * @Description: 增删改查模拟接口定义
  7. *
  8. * 模拟接口文件路径遵循规范:`/mock/[模块名]/[功能名].mock.js`
  9. * 更详细的文档请参考:https://github.com/pengzhanbo/vite-plugin-mock-dev-server
  10. */
  11. import { defineMock, backend, normalResponse, paginationReponse } from '@/../mock/shared/utils.js';
  12. import { crudDataList } from './data/crud.data.js';
  13. /**
  14. * 模拟API定义集合
  15. */
  16. export default defineMock([
  17. /**
  18. * 获取crud列表模拟接口
  19. * @method POST
  20. * @url /api/demo/crud/list
  21. * @body 返回分页形式的crud列表数据
  22. */
  23. {
  24. url: `${backend.demoService}/api/crud/list`,
  25. method: 'POST',
  26. enabled: true, // 是否启用接口模拟
  27. body: () => paginationReponse(crudDataList.value, crudDataList.value.length),
  28. },
  29. /**
  30. * 新增crud数据模拟接口
  31. * @method POST
  32. * @url /api/demo/crud/save
  33. * @body 接收并保存传入的crud数据,成功时返回正常响应,失败时返回错误信息
  34. */
  35. {
  36. url: `${backend.demoService}/api/crud/save`,
  37. method: 'POST',
  38. body: ({ body }) => {
  39. const { id } = body;
  40. let success = false;
  41. if (id) {
  42. crudDataList.value.push(body);
  43. success = true;
  44. }
  45. return success ? normalResponse() : normalResponse(null, -1, '操作失败');
  46. },
  47. },
  48. /**
  49. * 更新crud数据模拟接口
  50. * @method POST
  51. * @url /api/demo/crud/update
  52. * @body 根据id查找并更新指定的crud数据,若找到则更新,否则新增
  53. */
  54. {
  55. url: `${backend.demoService}/api/crud/update`,
  56. method: 'POST',
  57. body: ({ body }) => {
  58. const temp = body;
  59. const index = crudDataList.value.findIndex((post) => post.id === temp.id);
  60. if (index !== -1) {
  61. crudDataList.value.splice(index, 1, temp);
  62. } else {
  63. crudDataList.value.push(temp);
  64. }
  65. return normalResponse();
  66. },
  67. },
  68. /**
  69. * 删除crud数据模拟接口
  70. * @method POST
  71. * @url /api/demo/crud/delete
  72. * @body 根据id删除指定的crud数据,删除成功时返回正常响应,失败时返回错误信息
  73. */
  74. {
  75. url: `${backend.demoService}/api/crud/delete`,
  76. method: 'POST',
  77. body: ({ body }) => {
  78. const { id } = body;
  79. let success = false;
  80. const index = crudDataList.value.findIndex((post) => post.id === id);
  81. if (index !== -1) {
  82. crudDataList.value.splice(index, 1);
  83. success = true;
  84. }
  85. return success ? normalResponse() : normalResponse(null, -1, '操作失败');
  86. },
  87. },
  88. ]);