You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
29 lines
953 B
JavaScript
29 lines
953 B
JavaScript
"use strict";
|
|
|
|
const DataLoader = require("dataloader");
|
|
const syncpipe = require("syncpipe");
|
|
|
|
module.exports = function dataloaderFromKnexResults({ fetch, selectKey }) {
|
|
/* A `whereIn` query would return any results that were found, but *not* produce empty
|
|
* results for those that weren't. But DataLoader expects for exactly one item to be
|
|
* provided for each supplied ID, even if it doesn't exist.
|
|
*
|
|
* This abstraction deals with that by collecting the results from Knex, and then
|
|
* creating a DataLoader-compatible sequence that pulls from these results, leaving
|
|
* gaps for non-existent items.
|
|
*/
|
|
|
|
let selectKeyCallback = selectKey ?? ((item) => item.id);
|
|
|
|
return new DataLoader(async (keys) => {
|
|
let matches = await fetch(keys);
|
|
|
|
let byKey = syncpipe(matches, [
|
|
_ => _.map((record) => [ selectKeyCallback(record), record ]),
|
|
_ => Object.fromEntries(_)
|
|
]);
|
|
|
|
return keys.map((key) => byKey[key] ?? null);
|
|
});
|
|
};
|