catalogue.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class CatalogueService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Catalogue;
  8. }
  9. async create({ content, name, describe, status, url, date, column, bind }) {
  10. assert(name, '名称不存在');
  11. assert(date, '发布时间不存在');
  12. assert(status, '状态不存在');
  13. assert(bind, '绑定ID不存在');
  14. try {
  15. const res = await this.model.create({ content, name, describe, status, url, date, column, bind });
  16. return { errcode: 0, errmsg: 'ok', data: res };
  17. } catch (error) {
  18. throw error;
  19. }
  20. }
  21. async update({ id, content, name, describe, status, url, date, column, bind }) {
  22. assert(id, 'id不存在');
  23. try {
  24. await this.model.updateOne({ _id: id }, { content, name, describe, status, url, date, column, bind });
  25. return { errcode: 0, errmsg: 'ok', data: '' };
  26. } catch (error) {
  27. throw error;
  28. }
  29. }
  30. async delete({ id }) {
  31. assert(id, 'id不存在');
  32. try {
  33. await this.model.deleteOne({ _id: id });
  34. return { errcode: 0, errmsg: 'ok', data: '' };
  35. } catch (error) {
  36. throw error;
  37. }
  38. }
  39. async query({ skip, limit, name, status, date, column, bind }) {
  40. const filter = {};
  41. const arr = { name, status, date, column, bind };
  42. for (const e in arr) {
  43. const data = `{ "${e}": { "$regex": "${arr[e]}" } }`;
  44. if (arr[e]) {
  45. filter.$or = [];
  46. filter.$or.push(JSON.parse(data));
  47. }
  48. }
  49. try {
  50. const total = await this.model.find({ ...filter });
  51. let res;
  52. if (skip && limit) {
  53. res = await this.model.find({ ...filter }, { content: false, url: false }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  54. } else {
  55. res = await this.model.find({ ...filter }, { content: false, url: false });
  56. }
  57. return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
  58. } catch (error) {
  59. throw error;
  60. }
  61. }
  62. async fetch({ id }) {
  63. assert(id, 'id不存在');
  64. try {
  65. const res = await this.model.findOne({ _id: id });
  66. return { errcode: 0, errmsg: 'ok', data: res };
  67. } catch (error) {
  68. throw error;
  69. }
  70. }
  71. }
  72. module.exports = CatalogueService;