UNPKG

@pothos/plugin-dataloader

Version:

A Pothos plugin for attaching dataloader to object types

62 lines (61 loc) 2.14 kB
import { createContextCache, isThenable } from '@pothos/core'; import DataLoader from 'dataloader'; export function rejectErrors(val) { if (isThenable(val)) { return val.then(rejectErrors); } return val.map((item) => item instanceof Error ? Promise.reject(item) : item); } export function loadAndSort(load, toKey) { if (!toKey) { return load; } return async (keys, context, args, info) => { const list = await load(keys, context, args, info); const map = new Map(); const results = new Array(); for (const val of list) { if (val instanceof Error) { throw val; } if (val != null) { map.set(toKey(val), val); } } for (let i = 0; i < keys.length; i += 1) { var _map_get; results[i] = (_map_get = map.get(keys[i])) !== null && _map_get !== void 0 ? _map_get : null; } return results; }; } export function dataloaderGetter(loaderOptions, load, toKey, sort) { const loader = sort ? loadAndSort(load, typeof sort === "function" ? sort : toKey) : load; return createContextCache((context) => new DataLoader((keys) => loader(keys, context), loaderOptions)); } export function pathDataloaderGetter(loaderOptions, load, toKey, sort, byPath) { const cache = createContextCache(() => new Map()); const loader = sort ? loadAndSort(load, typeof sort === "function" ? sort : toKey) : load; return (args, ctx, info) => { const key = byPath ? cacheKey(info.path) : "*"; const map = cache(ctx); if (!map.has(key)) { map.set(key, new DataLoader((keys) => loader(keys, ctx, args, info), loaderOptions)); } return map.get(key); }; } export function cacheKey(path) { if (!path) { // Root return "*"; } let key = String(path.key); let current = path.prev; while (current) { key = `${typeof current.key === "number" ? "*" : current.key}.${key}`; current = current.prev; } return key; } //# sourceMappingURL=util.js.map