dataloader-hook
v0.0.1
Published
Modified version of [Facebook's dataloader](https://github.com/graphql/dataloader) with each dataloader scoped to it's async context automatically using Node's [AsyncLocalStorage feature](https://nodejs.org/api/async_context.html#class-asynclocalstorage).
Downloads
1
Readme
dataloader-hook
Modified version of Facebook's dataloader with each dataloader scoped to it's async context automatically using Node's AsyncLocalStorage feature. This allowed each dataloader to be used within a single request without having to create and then pass down the loaders via a resolvers context value or attach to a req object.
Why?
Reduces amount of code - no need to create all your dataloaders at the start of a new request, and no need to have to pass the dataloaders down via arguments, handy especially if you have lots of deep call stacks per request.
Allows functions or modules in your code to be more decoupled, by not needing users of the modules to have to know about the dataloaders, and require them to initiate them in the request middleware and pass it around to different modules/functions via arguments.
How it works
Ctx-dataloader will create a new dataloader and an async context when the .load/loadMany or any other method has been called, and the dataloader will then propagate throughout the callbacks and promise chains on the subsequent calls of that request/async context until finished.
Example
import { DataLoaderHook } from 'dataloader-hook'
// No need to load run this for each request! Each dataloader is automatically scoped to each request. Just directly import this loader anywhere in your code, and if its in the request/async context batching and caching will work correctly.
const userLoader = new DataLoaderHook((ids) => getUsers(ids))
async function getUserBestFriend(user) {
// 2. Looks up if there is a async context, because there is, the same loader will be used again, meaning there was only 1 db call for the entire request
const bestFriend = await userLoader.load(user.bestFriendId)
return bestFriend
}
async function getUserAndTheirBestFriend(userId) {
// 1. New request scoped dataloader is created on .load call
const user = await userLoader.load(postId)
const bestFriend = await getUserBestFriend(user)
return { ...user, bestFriend }
}
const app = express()
app.get('/user', async (req, res) => {
const user = await getUserAndTheirBestFriend(req.query.id)
return res.json(user)
})
app.listen(3000)