UNPKG

@pothos/plugin-dataloader

Version:

A Pothos plugin for attaching dataloader to object types

94 lines (93 loc) 2.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _export(target, all) { for(var name in all)Object.defineProperty(target, name, { enumerable: true, get: all[name] }); } _export(exports, { cacheKey: function() { return cacheKey; }, dataloaderGetter: function() { return dataloaderGetter; }, loadAndSort: function() { return loadAndSort; }, pathDataloaderGetter: function() { return pathDataloaderGetter; }, rejectErrors: function() { return rejectErrors; } }); const _core = require("@pothos/core"); const _dataloader = /*#__PURE__*/ _interop_require_default(require("dataloader")); function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function rejectErrors(val) { if ((0, _core.isThenable)(val)) { return val.then(rejectErrors); } return val.map((item)=>item instanceof Error ? Promise.reject(item) : item); } 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; }; } function dataloaderGetter(loaderOptions, load, toKey, sort) { const loader = sort ? loadAndSort(load, typeof sort === 'function' ? sort : toKey) : load; return (0, _core.createContextCache)((context)=>new _dataloader.default((keys)=>loader(keys, context), loaderOptions)); } function pathDataloaderGetter(loaderOptions, load, toKey, sort, byPath) { const cache = (0, _core.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.default((keys)=>loader(keys, ctx, args, info), loaderOptions)); } return map.get(key); }; } 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