adds sorting and limiting to findChats endpoint

This commit is contained in:
Pedro Howat 2024-08-21 15:49:47 -03:00
parent 76d4cc27b2
commit 34bcee441a
2 changed files with 69 additions and 13 deletions

View File

@ -1,37 +1,92 @@
// import { Logger } from '../../../../config/logger.config'; import { Document } from 'bson';
import { configService, Database } from '../../../../config/env.config';
import { Logger } from '../../../../config/logger.config';
import { dbserver } from '../../../../libs/db.connect';
import { InstanceDto } from '../../../dto/instance.dto'; import { InstanceDto } from '../../../dto/instance.dto';
import { WAMonitoringService } from '../../../services/monitor.service'; import { WAMonitoringService } from '../../../services/monitor.service';
// const logger = new Logger('KwikController'); const logger = new Logger('KwikController');
export class KwikController { export class KwikController {
constructor(private readonly waMonitor: WAMonitoringService) {} constructor(private readonly waMonitor: WAMonitoringService) {}
public async fetchChats({ instanceName }: InstanceDto) { public async fetchChats({ instanceName }: InstanceDto, limit: number, skip: number, sort: any) {
const chats = await this.waMonitor.waInstances[instanceName].repository.chat.find({ const db = configService.get<Database>('DATABASE');
where: { owner: instanceName }, const connection = dbserver.getClient().db(db.CONNECTION.DB_PREFIX_NAME + '-whatsapp-api');
}); const messages = connection.collection('messages');
const pipeline: Document[] = [
{ $match: { owner: instanceName } },
{
$group: {
_id: '$key.remoteJid',
lastAllMsgTimestamp: { $max: '$messageTimestamp' },
},
},
];
if (sort === 'asc') {
pipeline.push({ $sort: { lastAllMsgTimestamp: 1 } });
} else {
pipeline.push({ $sort: { lastAllMsgTimestamp: -1 } });
}
if (!isNaN(skip)) {
pipeline.push({ $skip: skip });
}
if (!isNaN(limit)) {
pipeline.push({ $limit: limit });
}
const msgs = await messages.aggregate(pipeline).toArray();
const mm = await Promise.all( const mm = await Promise.all(
chats.map(async (chat) => { msgs.map(async (msg) => {
const chat = await connection.collection('chats').findOne({ id: msg._id });
const lastMsg = await this.waMonitor.waInstances[instanceName].repository.message.find({ const lastMsg = await this.waMonitor.waInstances[instanceName].repository.message.find({
where: { where: {
owner: instanceName, owner: instanceName,
messageTimestamp: msg.lastAllMsgTimestamp,
key: { key: {
remoteJid: chat.id, remoteJid: chat.id,
}, },
}, },
limit: 1, limit: 1,
sort: {
messageTimestamp: -1,
},
}); });
return { const chat_data = {
id: chat.id, id: chat.id,
labels: chat.labels, labels: chat.labels,
owner: chat.owner, owner: chat.owner,
lastAllMsgTimestamp: lastMsg.length > 0 ? lastMsg[0].messageTimestamp : 0, last_message_timestamp: msg.lastAllMsgTimestamp,
message: lastMsg[0].message,
message_type: lastMsg[0].messageType,
phone_num: null,
profile_picture: null,
name: null,
type: null,
}; };
const info = chat.id.split('@');
logger.error(info);
if (info[1] == 'g.us') {
chat_data.type = 'GROUP';
} else {
const contact = await this.waMonitor.waInstances[instanceName].fetchContacts({
where: {
owner: instanceName,
id: chat.id,
},
});
chat_data.type = 'CONTACT';
chat_data.phone_num = info[0];
if (contact && contact.length > 0) {
chat_data.name = contact[0].pushName;
chat_data.profile_picture = contact[0].profilePictureUrl;
}
}
return chat_data;
}), }),
); );

View File

@ -23,7 +23,8 @@ export class KwikRouter extends RouterBroker {
request: req, request: req,
schema: null, schema: null,
ClassRef: InstanceDto, ClassRef: InstanceDto,
execute: (instance) => kwikController.fetchChats(instance), execute: (instance) =>
kwikController.fetchChats(instance, Number(req.query.limit), Number(req.query.skip), req.query.sort),
}); });
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);