Last active
December 8, 2021 19:50
-
-
Save iansu/89cc247679c8e098fc2f4044782eb9e6 to your computer and use it in GitHub Desktop.
Minimal Dataloader implementation
This file contains hidden or 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
/* | |
* This is a minimal implementation of Dataloader. This implementation leaves out the caching functionality | |
* and skips most of the error handling so it's not suitable to use in production. This is meant to help | |
* you understand how Dataloader works. Once you understand this code check out the full Dataloader code: | |
* https://github.com/graphql/dataloader | |
*/ | |
class Dataloader { | |
constructor(batchFunction) { | |
this.batchFunction = batchFunction; | |
this.batchKeys = []; | |
this.batchPromises = []; | |
} | |
async load(key) { | |
console.log(`load key: ${key}`); | |
if (this.batchKeys.length === 0) { | |
process.nextTick(() => this.dispatch()); | |
} | |
this.batchKeys.push(key); | |
const promise = new Promise((resolve, reject) => { | |
this.batchPromises.push({ resolve, reject }); | |
}); | |
return promise; | |
} | |
async dispatch() { | |
console.log(`batchKeys: ${this.batchKeys}`); | |
const results = await this.batchFunction(this.batchKeys); | |
for (let i = 0; i < this.batchPromises.length; i++) { | |
const callback = this.batchPromises[i]; | |
if (results[i] instanceof Error) { | |
callback.reject(results[i]); | |
} else { | |
callback.resolve(results[i]); | |
} | |
} | |
this.batchKeys = []; | |
this.batchPromises = []; | |
} | |
} | |
module.exports = Dataloader; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment