123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const { ObjectId } = require('mongoose').Types;
- const _ = require('lodash');
- const assert = require('assert');
- // 个人聊天房间表
- class Person_roomService extends CrudService {
- constructor(ctx) {
- super(ctx, 'person_room');
- this.model = this.ctx.model.PersonRoom;
- this.pc = this.ctx.model.PersonChat;
- }
- async query(query) {
- query = this.ctx.service.util.util.turnDateRangeQuery(this.ctx.service.util.util.turnFilter(query));
- const { p_id, skip = 0, limit = 0, ...info } = query;
- const condition = { ...info }; // last_time: { $exists: true },
- if (p_id) {
- condition.$or = [{ p1_id: p_id }, { p2_id: p_id }];
- }
- let data = await this.model.find(condition).skip(parseInt(skip)).limit(parseInt(limit));
- const aggQuery = [
- { $match: { room_id: { $in: data.map(i => ObjectId(i._id)) }, is_read: false, receiver_id: ObjectId(p_id) } },
- {
- $group: {
- _id: '$room_id',
- sum: { $sum: 1 },
- },
- },
- ];
- const notReads = await this.pc.aggregate(aggQuery);
- if (data.length > 0) data = JSON.parse(JSON.stringify(data));
- data = data.map(i => {
- const nr = notReads.find(f => ObjectId(f._id).equals(i._id));
- if (nr) i.not_read = nr.sum;
- return i;
- });
- const total = await this.model.count(condition);
- return { data, total };
- }
- async create(payload) {
- const { p1_id, p2_id, product_id } = payload;
- const obj = await this.model.findOne({ $or: [{ p1_id, p2_id }, { p1_id: p2_id, p2_id: p1_id }], product_id });
- if (obj) return obj;
- const res = await this.model.create(payload);
- return res;
- }
- }
- module.exports = Person_roomService;
|