freshyo/packages/db_helper_sqlite/src/lib/run-batched.ts
2026-08-01 20:18:42 +05:30

39 lines
1.1 KiB
TypeScript

/** Extracts the transaction handle type from any Drizzle db. */
type TxOf<DB> = DB extends {
transaction: (cb: (tx: infer Tx) => any, ...args: any[]) => any;
}
? Tx
: never;
/**
* Runs `runChunk` sequentially over `items` inside a single transaction,
* passing at most `n` items per call. All chunks commit together, or the
* whole thing rolls back.
*
* @param db Drizzle database instance.
* @param items Full array of values (e.g. product ids).
* @param n Max items per batch (keep under SQLite's 999 var limit).
* @param runChunk Async fn that runs your query for one chunk, using `tx`.
*/
export async function runBatched<
DB extends { transaction: (cb: (tx: any) => any, ...args: any[]) => any },
T,
R,
>(
db: DB,
items: readonly T[],
n: number,
runChunk: (tx: TxOf<DB>, chunk: T[]) => Promise<R>,
): Promise<R[]> {
if (n < 1) throw new RangeError("`n` must be >= 1");
const result = await db.transaction(async (tx: TxOf<DB>) => {
const out: R[] = [];
for (let i = 0; i < items.length; i += n) {
out.push(await runChunk(tx, items.slice(i, i + n)));
}
return out;
});
return result as R[];
}