patentchat.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/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 PatentchatService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'patentchat');
  11. this.model = this.ctx.model.Patent.Patentchat;
  12. }
  13. async query({ id }, { skip = 0, limit = 0 } = {}) {
  14. assert(id, '缺少用户信息');
  15. const data = await this.model.find({ $or: [{ sender_id: id }, { receiver_id: id }] }).sort({ 'meta.createdAt': 1 }).skip(parseInt(skip))
  16. .limit(parseInt(limit));
  17. return data;
  18. }
  19. async count({ id }) {
  20. assert(id, '缺少用户信息');
  21. const data = await this.model.count({ $or: [{ sender_id: id }, { receiver_id: id }] });
  22. return data;
  23. }
  24. async getChatList({ id }) {
  25. const data = await this.model.aggregate([
  26. { $match: { $or: [{ sender_id: ObjectId(id) }, { receiver_id: ObjectId(id) }] } },
  27. ]);
  28. const obj = {};
  29. for (const i of data) {
  30. const { sender_id, receiver_id } = i;
  31. let getArrId = '';
  32. if (ObjectId(sender_id).equals(id)) getArrId = receiver_id;
  33. else getArrId = sender_id;
  34. let midArr = _.get(obj, getArrId, []);
  35. console.log(getArrId, midArr);
  36. midArr = [ ...midArr, i ];
  37. obj[getArrId] = midArr;
  38. }
  39. const rData = [];
  40. for (const key in obj) {
  41. let arr = obj[key];
  42. arr = _.orderBy(arr, [ 'meta.createdAt' ], [ 'desc' ]);
  43. const head = _.head(arr);
  44. rData.push(head);
  45. }
  46. return rData;
  47. }
  48. async queryPersonChat({ sender_id, receiver_id }) {
  49. console.log(sender_id, receiver_id);
  50. assert(sender_id && receiver_id, '缺少对话双方信息');
  51. const data = await this.model.find({ $or: [{ sender_id, receiver_id }, { sender_id: receiver_id, receiver_id: sender_id }] }).sort({ 'meta.createdAt': 1 });
  52. return data;
  53. }
  54. }
  55. module.exports = PatentchatService;