discuss.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class DiscussService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Discuss;
  8. }
  9. async create({ source, target, msg, parentId, status }) {
  10. assert(source, 'source不存在');
  11. assert(target, 'target不存在');
  12. assert(msg, '内容不存在');
  13. assert(status, '状态不存在');
  14. try {
  15. const res = await this.model.create({ source, target, parentId, msg, status });
  16. return { errcode: 0, errmsg: 'ok', data: res };
  17. } catch (error) {
  18. throw error;
  19. }
  20. }
  21. async update({ id, source, target, msg, parentId, status }) {
  22. assert(id, 'id不存在');
  23. try {
  24. await this.model.updateOne({ _id: id }, { source, target, msg, parentId, status });
  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, source, target, status }) {
  40. const filter = {};
  41. const arr = { source, target, status };
  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 }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  54. } else {
  55. res = await this.model.find({ ...filter });
  56. }
  57. return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
  58. } catch (error) {
  59. throw error;
  60. }
  61. }
  62. }
  63. module.exports = DiscussService;