personRoom.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const { ObjectId } = require('mongoose').Types;
  5. const _ = require('lodash');
  6. const assert = require('assert');
  7. // 个人聊天房间表
  8. class PersonRoomService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'person_room');
  11. this.model = this.ctx.model.User.PersonRoom;
  12. this.pc = this.ctx.model.User.PersonChat;
  13. }
  14. async query(query) {
  15. query = this.ctx.service.util.util.turnDateRangeQuery(this.ctx.service.util.util.turnFilter(query));
  16. const { p_id, skip = 0, limit = 0, ...info } = query;
  17. const condition = { ...info }; // last_time: { $exists: true },
  18. if (p_id) {
  19. condition.$or = [{ p1_id: p_id }, { p2_id: p_id }];
  20. }
  21. let data = await this.model.find(condition).skip(parseInt(skip)).limit(parseInt(limit));
  22. const aggQuery = [
  23. { $match: { room_id: { $in: data.map(i => ObjectId(i._id)) }, is_read: false, receiver_id: ObjectId(p_id) } },
  24. {
  25. $group: {
  26. _id: '$room_id',
  27. sum: { $sum: 1 },
  28. },
  29. },
  30. ];
  31. const notReads = await this.pc.aggregate(aggQuery);
  32. if (data.length > 0) data = JSON.parse(JSON.stringify(data));
  33. data = data.map(i => {
  34. const nr = notReads.find(f => ObjectId(f._id).equals(i._id));
  35. if (nr) i.not_read = nr.sum;
  36. return i;
  37. });
  38. const total = await this.model.count(condition);
  39. return { data, total };
  40. }
  41. async create(payload) {
  42. const { p1_id, p2_id, product_id } = payload;
  43. const obj = await this.model.findOne({ $or: [{ p1_id, p2_id }, { p1_id: p2_id, p2_id: p1_id }], product_id });
  44. if (obj) return obj;
  45. const res = await this.model.create(payload);
  46. return res;
  47. }
  48. }
  49. module.exports = PersonRoomService;