toconfig.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class ToconfigService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Toconfig;
  8. }
  9. async create({ name, code, type, value }) {
  10. assert(name, '名称不存在');
  11. assert(code, '编码不存在');
  12. assert(value, '值不存在');
  13. try {
  14. const res = await this.model.findOne({ code });
  15. if (res) return { errcode: -1001, errmsg: '编码已存在', data: '' };
  16. const item = await this.model.create({ name, code, type, value });
  17. return { errcode: 0, errmsg: '', data: item };
  18. } catch (error) {
  19. throw error;
  20. }
  21. }
  22. async update({ id, name, type, value }) {
  23. assert(id, 'id不存在');
  24. try {
  25. const res = await this.model.findOne({ _id: id });
  26. if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' };
  27. await this.model.updateOne({ _id: id }, { name, type, value });
  28. return { errcode: 0, errmsg: '', data: 'update' };
  29. } catch (error) {
  30. throw error;
  31. }
  32. }
  33. async delete({ id }) {
  34. assert(id, 'id不存在');
  35. try {
  36. const res = await this.model.findOne({ _id: id });
  37. if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' };
  38. await this.model.remove({ _id: id });
  39. return { errcode: 0, errmsg: '', data: 'delete' };
  40. } catch (error) {
  41. throw error;
  42. }
  43. }
  44. async query({ skip, limit, name, code }) {
  45. const filter = {};
  46. if (name || code) filter.$or = [];
  47. if (name) filter.$or.push({ name: { $regex: name } });
  48. if (code) filter.$or.push({ code: { $regex: code } });
  49. try {
  50. let res;
  51. const total = await this.model.find({ ...filter });
  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: '', data: res, total: total.length };
  58. } catch (error) {
  59. throw error;
  60. }
  61. }
  62. }
  63. module.exports = ToconfigService;