praise.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const assert = require('assert');
  3. const Service = require('egg').Service;
  4. class PraiseService extends Service {
  5. constructor(ctx) {
  6. super(ctx);
  7. this.model = this.ctx.model.Praise;
  8. }
  9. async create({ source, target }) {
  10. assert(source, 'source不存在');
  11. assert(target, 'target不存在');
  12. try {
  13. const res = await this.model.create({ source, target });
  14. return { errcode: 0, errmsg: 'ok', data: res };
  15. } catch (error) {
  16. throw error;
  17. }
  18. }
  19. async update({ id, source, target }) {
  20. assert(id, 'id不存在');
  21. try {
  22. await this.model.updateOne({ _id: id }, { source, target });
  23. return { errcode: 0, errmsg: 'ok', data: '' };
  24. } catch (error) {
  25. throw error;
  26. }
  27. }
  28. async delete({ id }) {
  29. assert(id, 'id不存在');
  30. try {
  31. await this.model.deleteOne({ _id: id });
  32. return { errcode: 0, errmsg: 'ok', data: '' };
  33. } catch (error) {
  34. throw error;
  35. }
  36. }
  37. async query({ skip, limit, source, target }) {
  38. const filter = {};
  39. const arr = { source, target };
  40. for (const e in arr) {
  41. const data = `{ "${e}": { "$regex": "${arr[e]}" } }`;
  42. if (arr[e]) {
  43. filter.$or = [];
  44. filter.$or.push(JSON.parse(data));
  45. }
  46. }
  47. try {
  48. const total = await this.model.find({ ...filter });
  49. let res;
  50. if (skip && limit) {
  51. res = await this.model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit));
  52. } else {
  53. res = await this.model.find({ ...filter });
  54. }
  55. return { errcode: 0, errmsg: 'ok', data: res, total: total.length };
  56. } catch (error) {
  57. throw error;
  58. }
  59. }
  60. }
  61. module.exports = PraiseService;