thumbs.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const { ObjectId } = require('mongoose').Types;
  7. // 点赞
  8. class ThumbsService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'thumbs');
  11. this.model = this.ctx.model.Thumbs;
  12. }
  13. async create(body) {
  14. // 有就取消点赞,没有就点赞
  15. const { openid, article_id } = body;
  16. const count = await this.model.count({ openid, article_id });
  17. let res = false;
  18. if (count > 0) await this.model.deleteOne({ openid, article_id });
  19. else { await this.model.create(body); res = true; }
  20. return res;
  21. }
  22. /**
  23. * 查询某人对某些数据是否点赞
  24. * @param {Object} { ids, openid }
  25. */
  26. async getSum({ ids, openid }) {
  27. const match = { article_id: { $in: ids.map(i => ObjectId(i)) } };
  28. if (openid) match.openid = openid;
  29. const res = await this.model.aggregate([
  30. { $match: match },
  31. { $group: {
  32. _id: '$article_id',
  33. sum: { $sum: 1 },
  34. } },
  35. ]);
  36. return res;
  37. }
  38. }
  39. module.exports = ThumbsService;