Last active
January 20, 2022 15:00
-
-
Save garand/fd8a0e14e8c15e801f7e04f06a55ce2b to your computer and use it in GitHub Desktop.
Promise based DataLoader implementation for Remix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ./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