type.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class TypeService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Type;
  8. this.codeModel = this.ctx.model.Dictionary;
  9. }
  10. async create({ name, code }) {
  11. assert(name, '名称不存在');
  12. assert(code, '编码不存在');
  13. try {
  14. const obj = await this.model.findOne({ code });
  15. if (obj) return { errcode: -1001, errmsg: '编码已存在', data: '' };
  16. const res = await this.model.create({ name, code });
  17. return { errcode: 0, errmsg: 'ok', data: res };
  18. } catch (error) {
  19. throw error;
  20. }
  21. }
  22. async update({ id, name, code }) {
  23. assert(id, 'id不存在');
  24. try {
  25. await this.model.updateOne({ _id: id }, { name, code });
  26. return { errcode: 0, errmsg: 'ok', data: '' };
  27. } catch (error) {
  28. throw error;
  29. }
  30. }
  31. async delete({ id }) {
  32. console.log(id);
  33. assert(id, 'id不存在');
  34. try {
  35. const res = await this.model.findOne({ _id: id });
  36. const codeList = await this.codeModel.find({ parentCode: res.code });
  37. if (codeList.length > 0) await this.codeModel.remove({ parentCode: res.code });
  38. await this.model.remove({ _id: id });
  39. return { errcode: 0, errmsg: 'ok', data: '' };
  40. } catch (error) {
  41. throw error;
  42. }
  43. }
  44. async query({ skip, limit, code, name }) {
  45. const filter = {};
  46. if (code || name) filter.$or = [];
  47. if (code) filter.$or.push({ code: { $regex: code } });
  48. if (name) filter.$or.push({ name: { $regex: name } });
  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 = TypeService;