Skip to content

Instantly share code, notes, and snippets.

@iansu
Last active December 8, 2021 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iansu/89cc247679c8e098fc2f4044782eb9e6 to your computer and use it in GitHub Desktop.
Save iansu/89cc247679c8e098fc2f4044782eb9e6 to your computer and use it in GitHub Desktop.
Minimal Dataloader implementation
/*
* 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