Skip to content

Instantly share code, notes, and snippets.

@voby
Created May 24, 2018 10:37
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 voby/90440975c97b4dfc7bd742a5dd87effc to your computer and use it in GitHub Desktop.
Save voby/90440975c97b4dfc7bd742a5dd87effc to your computer and use it in GitHub Desktop.
import DataLoader from 'dataloader';
function indexResults(results, indexField, cacheKeyFn = key => key) {
const indexedResults = new Map();
results.forEach((res) => {
indexedResults.set(cacheKeyFn(res[indexField]), res);
});
return indexedResults;
}
function normalizeResults(keys, indexField, cacheKeyFn = key => key) {
return (results) => {
const indexedResults = indexResults(results, indexField, cacheKeyFn);
return keys.map(
val =>
indexedResults.get(cacheKeyFn(val)) ||
new Error(`Key not found : ${val}`),
);
};
}
const cacheKeyFn = key => key.toString();
async function knexLoader(knex, name, ids) {
const results = await knex(name).whereIn('id', ids);
return normalizeResults(ids, 'id', cacheKeyFn)(results);
}
class Loaders {
constructor(knex) {
this.loaders = {};
this.knex = knex;
}
table(name) {
if (this.loaders[name]) {
return this.loaders[name];
}
this.loaders[name] = new DataLoader(ids =>
knexLoader(this.knex, name, ids),
);
return this.loaders[name];
}
}
export default function createLoaders(knex) {
return new Loaders(knex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment