Skip to content

Instantly share code, notes, and snippets.

@wtrocki
Last active November 13, 2019 23:28
Show Gist options
  • Save wtrocki/7bbce8f132368df1668323956ac743b5 to your computer and use it in GitHub Desktop.
Save wtrocki/7bbce8f132368df1668323956ac743b5 to your computer and use it in GitHub Desktop.
GraphQL Data Loader Simplified
import DataLoader = require('dataloader');
/**
* Speciallized function that can utilize batching the data basing on
* DataLoader library
*
* @param context - resolver context object that will be used to apply new loader
* @param name - name of the object we want to load
* @param id - id of the object we want to load
*/
const batchLoadData = (name: string, id: string, context: any) => {
const keyName = `${name}DataLoader`;
if (!context[keyName]) {
context[keyName] = new DataLoader<string, any>((keys: string[]) => {
return this.db.batchRead(name, keys);
});
}
return context[keyName.load(id);
}
// Can be used in resolver as follows
batchLoadData('test', 3, context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment