Spaces:
Runtime error
Runtime error
File size: 1,846 Bytes
4327358 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
import { Knex } from 'knex';
import { ChatwootMessage, MessageMapping, WhatsAppMessage } from './types';
export class MessageMappingRepository {
static tableName = 'app_chatwoot_message_mappings';
constructor(
private readonly knex: Knex,
private readonly appPk: number,
) {}
get tableName() {
return MessageMappingRepository.tableName;
}
/**
* Creates a mapping between a Chatwoot message and a WhatsApp message
*/
upsertMapping(
chatwoot: Pick<ChatwootMessage, 'id'>,
whatsapp: Pick<WhatsAppMessage, 'id'>,
part: number,
): Promise<MessageMapping> {
return this.knex.transaction((trx) =>
this.upsertMappingWithTrx(trx, chatwoot, whatsapp, part),
);
}
async upsertMappingWithTrx(
trx: Knex.Transaction,
chatwoot: Pick<ChatwootMessage, 'id'>,
whatsapp: Pick<WhatsAppMessage, 'id'>,
part: number,
): Promise<MessageMapping> {
const [id] = await trx(this.tableName)
.insert({
app_pk: this.appPk,
chatwoot_message_id: chatwoot.id,
whatsapp_message_id: whatsapp.id,
part,
})
.onConflict([
'app_pk',
'chatwoot_message_id',
'whatsapp_message_id',
'part',
])
.merge()
.returning('id');
return {
id,
chatwoot_message_id: chatwoot.id,
whatsapp_message_id: whatsapp.id,
part: part,
};
}
async getByWhatsAppMessageId(id: number): Promise<MessageMapping | null> {
return this.knex(this.tableName)
.where({
app_pk: this.appPk,
whatsapp_message_id: id,
})
.first();
}
async getByChatwootMessageId(id: number): Promise<MessageMapping | null> {
return this.knex(this.tableName)
.where({
app_pk: this.appPk,
chatwoot_message_id: id,
})
.first();
}
}
|