Quickstart: Create a basic Batcher
masterTo use @yornaath/batshit, initialize a Batcher by providing a fetcher function, a resolver, and an optional scheduler. The Batcher deduplicates and batches requests made within a specific time window into a single call.
fetcher: An async function that receives an array of keys and returns the batched data.resolver: UseskeyResolverto identify how to extract unique keys from the data or how to map requests to results.scheduler: UseswindowScheduler(ms)to define the time window for batching. If omitted, it defaults to a window of 10ms.
This is ideal for reducing network overhead when multiple components or functions request data simultaneously.
import { Batcher, keyResolver, windowScheduler } from "@yornaath/batshit";
type User = { id: number; name: string };
const users = Batcher<User, number>({
fetcher: async (ids) => {
// ids is an array of the keys requested
return client.users.where({
userId_in: ids,
});
},
resolver: keyResolver("id"),
scheduler: windowScheduler(10), // Default and can be omitted.
});
// Requests made within the 10ms window will be batched into one call
const bob = users.fetch(1);
const alice = users.fetch(2);
const [bobData, aliceData] = await Promise.all([bob, alice]);