dictionary.js 2.1 KB

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