column.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. const res = await this.model.findOne({ _id: id });
  39. if (!res) return { errcode: -1001, errmsg: '数据不存在', data: '' };
  40. const content = await this.content.findOne({ bind: res.code });
  41. const menu = await this.menu.findOne({ column: res.code });
  42. const imgnews = await this.imgnews.findOne({ column: res.code });
  43. if (content || menu || imgnews) {
  44. let errmsg = '';
  45. if (content) errmsg += '(内容)';
  46. if (menu) errmsg += '(菜单)';
  47. if (imgnews) errmsg += '(图片新闻)';
  48. return { errcode: -1001, errmsg: `存在${errmsg}绑定关系,不能删除`, data: '' };
  49. }
  50. await this.model.remove({ _id: id });
  51. return { errcode: 0, errmsg: '', data: 'delete' };
  52. } catch (error) {
  53. throw error;
  54. }
  55. }
  56. async query({ skip, limit, code, name }) {
  57. const filter = {};
  58. if (name || code) filter.$or = [];
  59. if (code) filter.$or.push({ code: { $regex: code } });
  60. if (name) filter.$or.push({ name: { $regex: name } });
  61. try {
  62. let res;
  63. const total = await this.model.find({ ...filter });
  64. if (skip && limit) {
  65. res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  66. } else {
  67. res = await this.model.find({ ...filter });
  68. }
  69. return { errcode: 0, errmsg: '', data: res, total: total.length };
  70. } catch (error) {
  71. throw error;
  72. }
  73. }
  74. }
  75. module.exports = ColumnService;