imgtype.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class ImgtypeService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Imgtype;
  8. this.imgnews = this.ctx.model.Imgnews;
  9. }
  10. async create({ name, code }) {
  11. assert(name, '名称不存在');
  12. assert(code, '编码不存在');
  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 });
  17. return { errcode: 0, errmsg: '', data: item };
  18. } catch (error) {
  19. throw error;
  20. }
  21. }
  22. async update({ id, name }) {
  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 });
  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. const imgnews = await this.imgnews.findOne({ bind: res.code });
  39. if (imgnews) return { errcode: -1001, errmsg: '存在绑定关系,不能删除', data: '' };
  40. await this.model.remove({ _id: id });
  41. return { errcode: 0, errmsg: '', data: 'delete' };
  42. } catch (error) {
  43. throw error;
  44. }
  45. }
  46. async query({ skip, limit, name, code }) {
  47. const filter = {};
  48. if (name || code) filter.$or = [];
  49. if (name) filter.$or.push({ code: { $regex: name } });
  50. if (code) filter.$or.push({ name: { $regex: code } });
  51. try {
  52. let res;
  53. const total = await this.model.find({ ...filter });
  54. if (skip && limit) {
  55. res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  56. } else {
  57. res = await this.model.find({ ...filter });
  58. }
  59. return { errcode: 0, errmsg: '', data: res, total: total.length };
  60. } catch (error) {
  61. throw error;
  62. }
  63. }
  64. }
  65. module.exports = ImgtypeService;