| 10 | const logger = createLogger('invoice-repository') |
| 11 | |
| 12 | export class InvoiceRepository implements IInvoiceRepository { |
| 13 | public constructor(private readonly dbClient: DatabaseClient) {} |
| 14 | |
| 15 | public async confirmInvoice( |
| 16 | invoiceId: string, |
| 17 | amountPaid: bigint, |
| 18 | confirmedAt: Date, |
| 19 | client: DatabaseClient = this.dbClient, |
| 20 | ): Promise<void> { |
| 21 | logger('confirming invoice %s at %s: %s', invoiceId, confirmedAt, amountPaid) |
| 22 | |
| 23 | try { |
| 24 | await client.raw('select confirm_invoice(?, ?, ?)', [invoiceId, amountPaid.toString(), confirmedAt.toISOString()]) |
| 25 | } catch (error) { |
| 26 | logger.error('Unable to confirm invoice. Reason:', error) |
| 27 | |
| 28 | throw error |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | public async findById(id: string, client: DatabaseClient = this.dbClient): Promise<Invoice | undefined> { |
| 33 | const [dbInvoice] = await client<DBInvoice>('invoices').where('id', id).select() |
| 34 | |
| 35 | if (!dbInvoice) { |
| 36 | return |
| 37 | } |
| 38 | |
| 39 | return fromDBInvoice(dbInvoice) |
| 40 | } |
| 41 | |
| 42 | public async findPendingInvoices(offset = 0, limit = 10, client: DatabaseClient = this.dbClient): Promise<Invoice[]> { |
| 43 | // Order by created_at ASC for deterministic FIFO polling: oldest pending |
| 44 | // invoices are picked up first, and the scan is index-only against |
| 45 | // invoices_pending_created_at_idx (partial on status = 'pending'). |
| 46 | const dbInvoices = await client<DBInvoice>('invoices') |
| 47 | .where('status', InvoiceStatus.PENDING) |
| 48 | .orderBy('created_at', 'asc') |
| 49 | .offset(offset) |
| 50 | .limit(limit) |
| 51 | .select() |
| 52 | |
| 53 | return dbInvoices.map(fromDBInvoice) |
| 54 | } |
| 55 | |
| 56 | public updateStatus(invoice: Invoice, client: DatabaseClient = this.dbClient): Promise<Invoice | undefined> { |
| 57 | logger('updating invoice status: %o', invoice) |
| 58 | |
| 59 | const query = client<DBInvoice>('invoices') |
| 60 | .update({ |
| 61 | status: invoice.status, |
| 62 | updated_at: new Date(), |
| 63 | }) |
| 64 | .where('id', invoice.id) |
| 65 | .limit(1) |
| 66 | .returning(['*']) |
| 67 | |
| 68 | return { |
| 69 | then: <T1, T2>( |
nothing calls this directly
no outgoing calls
no test coverage detected