Skip to content

Commit d31d6fa

Browse files
committed
refactor: replace JSON path queries with raw SQL in Baileys and Chatwoot services to improve message retrieval and update logic
1 parent edbf360 commit d31d6fa

File tree

2 files changed

+56
-68
lines changed

2 files changed

+56
-68
lines changed

src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Lines changed: 35 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -484,9 +484,13 @@ export class BaileysStartupService extends ChannelStartupService {
484484

485485
private async getMessage(key: proto.IMessageKey, full = false) {
486486
try {
487-
const webMessageInfo = (await this.prismaRepository.message.findMany({
488-
where: { instanceId: this.instanceId, key: { path: ['id'], equals: key.id } },
489-
})) as unknown as proto.IWebMessageInfo[];
487+
// Use raw SQL to avoid JSON path issues
488+
const webMessageInfo = (await this.prismaRepository.$queryRaw`
489+
SELECT * FROM "Message"
490+
WHERE "instanceId" = ${this.instanceId}
491+
AND "key"->>'id' = ${key.id}
492+
`) as proto.IWebMessageInfo[];
493+
490494
if (full) {
491495
return webMessageInfo[0];
492496
}
@@ -1459,9 +1463,14 @@ export class BaileysStartupService extends ChannelStartupService {
14591463
let findMessage: any;
14601464
const configDatabaseData = this.configService.get<Database>('DATABASE').SAVE_DATA;
14611465
if (configDatabaseData.HISTORIC || configDatabaseData.NEW_MESSAGE) {
1462-
findMessage = await this.prismaRepository.message.findFirst({
1463-
where: { instanceId: this.instanceId, key: { path: ['id'], equals: key.id } },
1464-
});
1466+
// Use raw SQL to avoid JSON path issues
1467+
const messages = (await this.prismaRepository.$queryRaw`
1468+
SELECT * FROM "Message"
1469+
WHERE "instanceId" = ${this.instanceId}
1470+
AND "key"->>'id' = ${key.id}
1471+
LIMIT 1
1472+
`) as any[];
1473+
findMessage = messages[0] || null;
14651474

14661475
if (findMessage) message.messageId = findMessage.id;
14671476
}
@@ -4427,24 +4436,23 @@ export class BaileysStartupService extends ChannelStartupService {
44274436
private async updateMessagesReadedByTimestamp(remoteJid: string, timestamp?: number): Promise<number> {
44284437
if (timestamp === undefined || timestamp === null) return 0;
44294438

4430-
const result = await this.prismaRepository.message.updateMany({
4431-
where: {
4432-
AND: [
4433-
{ key: { path: ['remoteJid'], equals: remoteJid } },
4434-
{ key: { path: ['fromMe'], equals: false } },
4435-
{ messageTimestamp: { lte: timestamp } },
4436-
{ OR: [{ status: null }, { status: status[3] }] },
4437-
],
4438-
},
4439-
data: { status: status[4] },
4440-
});
4439+
// Use raw SQL to avoid JSON path issues
4440+
const result = await this.prismaRepository.$executeRaw`
4441+
UPDATE "Message"
4442+
SET "status" = ${status[4]}
4443+
WHERE "instanceId" = ${this.instanceId}
4444+
AND "key"->>'remoteJid' = ${remoteJid}
4445+
AND ("key"->>'fromMe')::boolean = false
4446+
AND "messageTimestamp" <= ${timestamp}
4447+
AND ("status" IS NULL OR "status" = ${status[3]})
4448+
`;
44414449

44424450
if (result) {
4443-
if (result.count > 0) {
4451+
if (result > 0) {
44444452
this.updateChatUnreadMessages(remoteJid);
44454453
}
44464454

4447-
return result.count;
4455+
return result;
44484456
}
44494457

44504458
return 0;
@@ -4453,15 +4461,14 @@ export class BaileysStartupService extends ChannelStartupService {
44534461
private async updateChatUnreadMessages(remoteJid: string): Promise<number> {
44544462
const [chat, unreadMessages] = await Promise.all([
44554463
this.prismaRepository.chat.findFirst({ where: { remoteJid } }),
4456-
this.prismaRepository.message.count({
4457-
where: {
4458-
AND: [
4459-
{ key: { path: ['remoteJid'], equals: remoteJid } },
4460-
{ key: { path: ['fromMe'], equals: false } },
4461-
{ status: { equals: status[3] } },
4462-
],
4463-
},
4464-
}),
4464+
// Use raw SQL to avoid JSON path issues
4465+
this.prismaRepository.$queryRaw`
4466+
SELECT COUNT(*)::int as count FROM "Message"
4467+
WHERE "instanceId" = ${this.instanceId}
4468+
AND "key"->>'remoteJid' = ${remoteJid}
4469+
AND ("key"->>'fromMe')::boolean = false
4470+
AND "status" = ${status[3]}
4471+
`.then((result: any[]) => result[0]?.count || 0),
44654472
]);
44664473

44674474
if (chat && chat.unreadMessages !== unreadMessages) {

src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts

Lines changed: 21 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1561,53 +1561,34 @@ export class ChatwootService {
15611561
return;
15621562
}
15631563

1564-
// Use the message ID directly instead of JSON path query
1565-
await this.prismaRepository.message.updateMany({
1566-
where: {
1567-
AND: [
1568-
{ instanceId: instance.instanceId },
1569-
{
1570-
OR: [
1571-
{ id: message.id }, // Use the actual message ID if available
1572-
// Fallback to raw query if needed
1573-
{
1574-
key: {
1575-
path: ['id'],
1576-
equals: key.id,
1577-
},
1578-
},
1579-
],
1580-
},
1581-
],
1582-
},
1583-
data: {
1584-
chatwootMessageId: chatwootMessageIds.messageId,
1585-
chatwootConversationId: chatwootMessageIds.conversationId,
1586-
chatwootInboxId: chatwootMessageIds.inboxId,
1587-
chatwootContactInboxSourceId: chatwootMessageIds.contactInboxSourceId,
1588-
chatwootIsRead: chatwootMessageIds.isRead,
1589-
},
1590-
});
1564+
// Use raw SQL to avoid JSON path issues
1565+
await this.prismaRepository.$executeRaw`
1566+
UPDATE "Message"
1567+
SET
1568+
"chatwootMessageId" = ${chatwootMessageIds.messageId},
1569+
"chatwootConversationId" = ${chatwootMessageIds.conversationId},
1570+
"chatwootInboxId" = ${chatwootMessageIds.inboxId},
1571+
"chatwootContactInboxSourceId" = ${chatwootMessageIds.contactInboxSourceId},
1572+
"chatwootIsRead" = ${chatwootMessageIds.isRead || false}
1573+
WHERE "instanceId" = ${instance.instanceId}
1574+
AND "key"->>'id' = ${key.id}
1575+
`;
15911576

15921577
if (this.isImportHistoryAvailable()) {
15931578
chatwootImport.updateMessageSourceID(chatwootMessageIds.messageId, key.id);
15941579
}
15951580
}
15961581

15971582
private async getMessageByKeyId(instance: InstanceDto, keyId: string): Promise<MessageModel> {
1598-
// Try to find message using a more compatible approach
1599-
const messages = await this.prismaRepository.message.findFirst({
1600-
where: {
1601-
instanceId: instance.instanceId,
1602-
// Use raw query to avoid JSON path issues
1603-
key: {
1604-
path: ['id'],
1605-
equals: keyId,
1606-
},
1607-
},
1608-
});
1609-
1610-
return messages || null;
1583+
// Use raw SQL query to avoid JSON path issues with Prisma
1584+
const messages = await this.prismaRepository.$queryRaw`
1585+
SELECT * FROM "Message"
1586+
WHERE "instanceId" = ${instance.instanceId}
1587+
AND "key"->>'id' = ${keyId}
1588+
LIMIT 1
1589+
`;
1590+
1591+
return (messages as MessageModel[])[0] || null;
16111592
}
16121593

16131594
private async getReplyToIds(

0 commit comments

Comments
 (0)