import { Collection, ObjectId } from "mongodb"; import { getDb } from "../index"; import type { RetryAnalyzeDoc, RetryAnalyzeWithId } from "./retryAnalyze.types"; const COLLECTION_NAME = "retryAnalyze"; export const getRetryAnalyzeCollection = (): Collection => { return getDb().collection(COLLECTION_NAME); }; export const getAllRetryAnalyzeDocs = async (): Promise< RetryAnalyzeWithId[] > => { return getRetryAnalyzeCollection() .find({ $or: [{ retry: { $lt: 5 } }, { retry: { $exists: false } }], }) .toArray(); }; export const insertRetryAnalyzeDoc = async ( doc: Omit, ): Promise => { const result = await getRetryAnalyzeCollection().insertOne(doc); return result.insertedId; }; export const upsertRetryAnalyzeDoc = async ( doc: Pick, ): Promise => { const now = new Date(); const result = await getRetryAnalyzeCollection().updateOne( { callSid: doc.callSid }, { $set: { errorLog: doc.errorLog, updatedAt: now, }, $setOnInsert: { createdAt: now, clientId: doc.clientId, retry: 0, }, }, { upsert: true }, ); if (result.matchedCount > 0) { await getRetryAnalyzeCollection().updateOne( { callSid: doc.callSid }, { $inc: { retry: 1 } }, ); } return result.upsertedId || null; }; export const deleteRetryAnalyzeDocById = async ( id: ObjectId, ): Promise => { const result = await getRetryAnalyzeCollection().deleteOne({ _id: id }); return result.deletedCount === 1; }; export const deleteRetryAnalyzeDocByCallSid = async ( callSid: string, ): Promise => { const result = await getRetryAnalyzeCollection().deleteOne({ callSid }); return result.deletedCount === 1; }; export const updateRetryAnalyzeErrorLog = async ( id: ObjectId, errorLog: string, ): Promise => { const result = await getRetryAnalyzeCollection().updateOne( { _id: id }, { $set: { errorLog, updatedAt: new Date() }, $inc: { retry: 1 }, }, ); return result.modifiedCount === 1; };