Create a new DataLoader per request
mainTo ensure security and data isolation between different users (especially when access permissions vary), it is a recommended pattern to create a new instance of all DataLoaders for every incoming web request.
A common way to manage this is to create a factory function that returns an object containing all necessary loaders. This object can then be passed through your application logic, for example, as part of the rootValue in a GraphQL request.
function createLoaders(authToken) {
return {
users: new DataLoader(ids => genUsers(authToken, ids)),
cdnUrls: new DataLoader(rawUrls => genCdnUrls(authToken, rawUrls)),
stories: new DataLoader(keys => genStories(authToken, keys)),
};
}
// When handling an incoming web request:
const loaders = createLoaders(request.query.authToken);
// Then, within application logic:
const user = await loaders.users.load(4);
const pic = await loaders.cdnUrls.load(user.rawPicUrl);