type.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. assert(id, 'id不存在');
  33. try {
  34. const res = await this.model.findOne({ _id: id });
  35. const codeList = await this.codeModel.find({ parentCode: res.code });
  36. if (codeList.length > 0) await this.codeModel.remove({ parentCode: res.code });
  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, 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. try {
  49. const total = await this.model.find({ ...filter });
  50. let res;
  51. if (skip && limit) {
  52. res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  53. } else {
  54. res = await this.model.find({ ...filter });
  55. }
  56. return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
  57. } catch (error) {
  58. throw error;
  59. }
  60. }
  61. }
  62. module.exports = TypeService;