Spaces:
Runtime error
Runtime error
File size: 1,716 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 |
import { Knex } from 'knex';
import { ChatWootCombinedKey, ChatwootMessage } from './types';
export class ChatwootMessageRepository {
static tableName = 'app_chatwoot_chatwoot_messages';
constructor(
private readonly knex: Knex,
private readonly appPk: number,
) {}
get tableName() {
return ChatwootMessageRepository.tableName;
}
async upsertWithTrx(
trx: Knex.Transaction,
message: Omit<ChatwootMessage, 'id'>,
): Promise<ChatwootMessage> {
const [id] = await trx(this.tableName)
.insert({
...message,
app_pk: this.appPk,
})
.onConflict(['app_pk', 'conversation_id', 'message_id'])
.merge()
.returning('id');
return { ...message, ...id };
}
/**
* Gets a message by its id
*/
async getById(id: number): Promise<ChatwootMessage | null> {
return this.knex(this.tableName)
.where({
app_pk: this.appPk,
id: id,
})
.first();
}
async getByCombinedKey(key: ChatWootCombinedKey): Promise<ChatwootMessage[]> {
return this.knex(this.tableName)
.where({
app_pk: this.appPk,
conversation_id: key.conversation_id,
message_id: key.message_id,
})
.select('*');
}
/**
* Deletes messages older than the specified date
* @param date Date before which messages should be removed
* @param trx Optional transaction object
* @returns Number of deleted messages
*/
async deleteMessagesOlderThan(
trx: Knex.Transaction,
date: Date,
): Promise<number> {
const result = await trx(this.tableName)
.where('app_pk', this.appPk)
.andWhere('timestamp', '<', date)
.del();
return result;
}
}
|