column.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class ColumnService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Column;
  8. this.content = this.ctx.model.Content;
  9. this.menu = this.ctx.model.Menu;
  10. this.imgnews = this.ctx.model.Imgnews;
  11. }
  12. async create({ name, code }) {
  13. assert(name, '名称不存在');
  14. assert(code, '编码不存在');
  15. try {
  16. const res = await this.model.findOne({ code });
  17. if (res) return { errcode: -1001, errmsg: '编码已存在', data: '' };
  18. const item = await this.model.create({ name, code });
  19. return { errcode: 0, errmsg: '', data: item };
  20. } catch (error) {
  21. throw error;
  22. }
  23. }
  24. async update({ id, name }) {
  25. assert(id, 'id不存在');
  26. try {
  27. const res = await this.model.findOne({ _id: id });
  28. if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' };
  29. await this.model.updateOne({ _id: id }, { name });
  30. return { errcode: 0, errmsg: '', data: 'update' };
  31. } catch (error) {
  32. throw error;
  33. }
  34. }
  35. async delete({ id }) {
  36. assert(id, 'id不存在');
  37. try {
  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, code, name }) {
  45. const filter = {};
  46. if (name || code) filter.$or = [];
  47. if (code) filter.$or.push({ code: { $regex: code } });
  48. if (name) filter.$or.push({ name: { $regex: name } });
  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 = ColumnService;