Last active
November 13, 2019 23:28
-
-
Save wtrocki/7bbce8f132368df1668323956ac743b5 to your computer and use it in GitHub Desktop.
GraphQL Data Loader Simplified
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
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