Skip to content

Instantly share code, notes, and snippets.

@garand
Last active January 20, 2022 15:00
Show Gist options
  • Save garand/fd8a0e14e8c15e801f7e04f06a55ce2b to your computer and use it in GitHub Desktop.
Save garand/fd8a0e14e8c15e801f7e04f06a55ce2b to your computer and use it in GitHub Desktop.
Promise based DataLoader implementation for Remix
// ./server/index.js
createRequestHandler({
build,
mode: MODE,
getLoadContext() {
return {
loader: PromiseLoader(),
};
},
})(req, res, next);
// ./app/routes/index.tsx
export const loader: LoaderFunction = async ({ request, context }) => {
const sdkInstance = await getSDKInstance(request);
return {
user: await context.loader.load(["user", () => sdkInstance.user.get()]),
};
};
// ./utils/promiseLoader.ts
import DataLoader from "dataloader";
type PromiseLoaderKey = [cacheKey: string, promise: () => Promise<unknown>];
export function PromiseLoader() {
return new DataLoader<PromiseLoaderKey, Response, string>(promiseLoader, {
cacheKeyFn: ([cacheKey]) => cacheKey,
});
}
function promiseLoader(keys: PromiseLoaderKey[]) {
return new Promise((resolve, reject) => {
const values = Promise.all(
keys.map(async ([cacheKey, promise]) => {
console.log("[PromiseLoader] Awaiting Promise: ", cacheKey);
return await promise();
})
);
resolve(values);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment