File size: 1,081 Bytes
5bd4e3a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import { randomUUID } from "node:crypto";
import type { Account, AccountKind, LedgerStore, Transaction } from "./types.js";
export class MemoryStore implements LedgerStore {
accounts: Account[] = [];
txs: Transaction[] = [];
async getOrCreateAccount(userId: string, kind: AccountKind, currency: string) {
let a = this.accounts.find((x) => x.user_id === userId && x.kind === kind && x.currency === currency);
if (!a) { a = { id: randomUUID(), user_id: userId, kind, currency }; this.accounts.push(a); }
return a;
}
async findTransactionByKey(userId: string, key: string) {
return this.txs.find((t) => t.user_id === userId && t.idempotency_key === key) ?? null;
}
async insertTransaction(tx: Transaction) { this.txs.push(structuredClone(tx)); }
async balance(accountId: string) {
return this.txs.flatMap((t) => t.postings).filter((p) => p.account_id === accountId).reduce((s, p) => s + p.amount, 0);
}
async listTransactions(userId: string, limit = 50) {
return this.txs.filter((t) => t.user_id === userId).slice(-limit).reverse();
}
}
|