roleBindMenu.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class RoleBindMenuService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.RoleBindMenu;
  8. }
  9. async bind({ roleCode, menuCode }) {
  10. assert(roleCode, '缺少角色编码');
  11. assert(menuCode, '缺少菜单编码');
  12. try {
  13. const bind = await this.model.findOne({ roleCode, menuCode });
  14. if (bind) return { errcode: -1001, errmsg: '不能重复绑定', data: '' };
  15. const res = await this.model.create({ roleCode, menuCode });
  16. return { errcode: 0, errmsg: '', data: res };
  17. } catch (error) {
  18. throw error;
  19. }
  20. }
  21. async unbind({ id }) {
  22. assert(id, '缺少ID');
  23. try {
  24. const bind = await this.model.findOne({ _id: id });
  25. if (!bind) return { errcode: -1001, errmsg: '数据不存在', data: '' };
  26. await this.model.deleteOne({ _id: id });
  27. return { errcode: 0, errmsg: 'ok', data: 'unbind' };
  28. } catch (error) {
  29. throw error;
  30. }
  31. }
  32. async queryBind({ skip, limit, roleCode, menuCode }) {
  33. const filter = {};
  34. if (menuCode) filter.menuCode = menuCode;
  35. if (roleCode) filter.roleCode = roleCode;
  36. try {
  37. const total = await this.model.find({ ...filter });
  38. let res;
  39. if (skip && limit) {
  40. res = await this.model.find({ ...filter }).skip(skip * limit).limit(limit);
  41. } else {
  42. res = await this.model.find({ ...filter });
  43. }
  44. return { errcode: 0, errmsg: '', data: res, total: total.length };
  45. } catch (error) {
  46. throw error;
  47. }
  48. }
  49. async batchBind({ menuCode, ids = [] }) {
  50. try {
  51. const res = await Promise.all(
  52. ids.filter(async e => {
  53. const bind = await this.model.findOne({ menuCode, roleCode: e });
  54. if (!bind) await this.model.create({ menuCode, roleCode: e });
  55. })
  56. );
  57. return { errcode: 0, errmsg: '', data: res };
  58. } catch (error) {
  59. throw error;
  60. }
  61. }
  62. async batchUnBind({ menuCode, ids = [] }) {
  63. try {
  64. const res = await Promise.all(
  65. ids.filter(async e => {
  66. const bind = await this.model.findOne({ menuCode, roleCode: e });
  67. if (bind) await this.model.deleteOne({ menuCode, roleCode: e });
  68. })
  69. );
  70. return { errcode: 0, errmsg: '', data: res };
  71. } catch (error) {
  72. throw error;
  73. }
  74. }
  75. }
  76. module.exports = RoleBindMenuService;