menu.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class MenuService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Menu;
  8. this.column = this.ctx.model.Column;
  9. this.pages = this.ctx.model.Pages;
  10. }
  11. async create({ name, code, sort, type, url, column, pages }) {
  12. assert(name, '名称不存在');
  13. assert(code, '编码不存在');
  14. assert(type, '类型不存在');
  15. try {
  16. const res = await this.model.findOne({ code });
  17. if (res) return { errcode: -1001, errmsg: '编码已存在', data: '' };
  18. const item = await this.model.create({ name, code, sort, type, url, column, pages });
  19. return { errcode: 0, errmsg: '', data: item };
  20. } catch (error) {
  21. throw error;
  22. }
  23. }
  24. async update({ id, name, sort, type, url, column, pages }) {
  25. assert(id, 'id不存在');
  26. try {
  27. const res = await this.model.findOne({ _id: id });
  28. if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' };
  29. await this.model.updateOne({ _id: id }, { name, sort, type, url, column, pages });
  30. return { errcode: 0, errmsg: '', data: 'update' };
  31. } catch (error) {
  32. throw error;
  33. }
  34. }
  35. async delete({ id }) {
  36. assert(id, 'id不存在');
  37. try {
  38. const res = await this.model.findOne({ _id: id });
  39. if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' };
  40. const column = await this.column.findOne({ bind: res.code });
  41. const pages = await this.pages.findOne({ bind: res.code });
  42. if (column || pages) return { errcode: -1001, errmsg: '存在绑定关系,不能删除', data: '' };
  43. await this.model.remove({ _id: id });
  44. return { errcode: 0, errmsg: '', data: 'delete' };
  45. } catch (error) {
  46. throw error;
  47. }
  48. }
  49. async query({ skip, limit, name, code }) {
  50. const filter = {};
  51. if (name || code) filter.$or = [];
  52. if (name) filter.$or.push({ name: { $regex: name } });
  53. if (code) filter.$or.push({ code: { $regex: code } });
  54. try {
  55. let res;
  56. const total = await this.model.find({ ...filter });
  57. if (skip && limit) {
  58. res = await this.model.find({ ...filter })
  59. .skip(Number(skip) * Number(limit))
  60. .limit(Number(limit))
  61. .sort({ date: 1 });
  62. } else {
  63. res = await this.model.find({ ...filter });
  64. }
  65. return { errcode: 0, errmsg: '', data: res, total: total.length };
  66. } catch (error) {
  67. throw error;
  68. }
  69. }
  70. }
  71. module.exports = MenuService;