master
1import { TaskName } from './task.js'
2
3export function createBatcher(next: (taskName: TaskName, params: any) => void) {
4 const batches = new Map<TaskName, string[]>()
5
6 function batch(paginate: TaskName, batch: TaskName, maxPerBatch = 50) {
7 return function (count: number, id: string) {
8 if (count == 0) {
9 return
10 }
11 if (count > 100) {
12 next(paginate, { id })
13 } else {
14 let ids = batches.get(batch) ?? []
15 ids.push(id)
16 if (ids.length >= maxPerBatch) {
17 next(batch, { ids })
18 ids = []
19 }
20 batches.set(batch, ids)
21 }
22 }
23 }
24
25 function flush() {
26 for (const [batch, ids] of batches.entries()) {
27 next(batch, { ids })
28 batches.delete(batch)
29 }
30 }
31
32 return { batch, flush }
33}
34
35export type BatchFn = ReturnType<typeof createBatcher>['batch']