Created
May 24, 2018 10:37
-
-
Save voby/90440975c97b4dfc7bd742a5dd87effc to your computer and use it in GitHub Desktop.
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 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