role.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class RoleService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Role;
  8. this.UserBindRoleModel = this.ctx.model.UserBindRole;
  9. this.RoleBindMenuModel = this.ctx.model.RoleBindMenu;
  10. }
  11. async create({ name, code }) {
  12. assert(name, '缺少名称');
  13. assert(code, '缺少编码');
  14. const role = await this.model.findOne({ code });
  15. if (role) return { errcode: -1001, errmsg: '编码已存在' };
  16. try {
  17. const res = await this.model.create({ name, code });
  18. return { errcode: 0, errmsg: '', data: res };
  19. } catch (error) {
  20. throw error;
  21. }
  22. }
  23. async update({ id, name }) {
  24. assert(id, '缺少ID');
  25. try {
  26. const user = await this.model.findOne({ _id: id });
  27. if (!user) return { errcode: -1001, errmsg: '角色不存在', data: '' };
  28. await this.model.updateOne({ _id: id }, { name });
  29. return { errcode: 0, errmsg: '', data: 'update' };
  30. } catch (error) {
  31. throw error;
  32. }
  33. }
  34. async delete({ id }) {
  35. assert(id, '缺少ID');
  36. try {
  37. const role = await this.model.findOne({ _id: id });
  38. if (!role) return { errcode: -1001, errmsg: '角色不存在', data: '' };
  39. await this.UserBindRoleModel.find({ roleCode: role.code }).remove();
  40. await this.RoleBindMenuModel.find({ roleCode: role.code }).remove();
  41. await this.model.deleteOne({ _id: id });
  42. return { errcode: 0, errmsg: 'ok', data: 'delete' };
  43. } catch (error) {
  44. throw error;
  45. }
  46. }
  47. async query({ skip, limit, name, code }) {
  48. const filter = {};
  49. if (name || code) filter.$or = [];
  50. if (code) filter.$or.push({ code: { $regex: code } });
  51. if (name) filter.$or.push({ name: { $regex: name } });
  52. try {
  53. const total = await this.model.find({ ...filter });
  54. let res;
  55. if (skip && limit) {
  56. res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  57. } else {
  58. res = await this.model.find({ ...filter });
  59. }
  60. return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
  61. } catch (error) {
  62. throw error;
  63. }
  64. }
  65. }
  66. module.exports = RoleService;