UNPKG

@pothos/plugin-dataloader

Version:

A Pothos plugin for attaching dataloader to object types

71 lines (70 loc) 3.03 kB
import { RootFieldBuilder } from '@pothos/core'; import { pathDataloaderGetter, rejectErrors } from './util.js'; const fieldBuilderProto = RootFieldBuilder.prototype; fieldBuilderProto.loadable = function loadable({ load, sort, loaderOptions, resolve, type, byPath, ...options }) { const getLoader = pathDataloaderGetter(loaderOptions, (keys, ctx, args, info) => load(keys, ctx, args, info), undefined, sort, byPath); return this.field({ ...options, type, // @ts-expect-error types don't match because this handles both lists and single objects resolve: async (parent, args, context, info) => { const ids = await resolve(parent, args, context, info); if (ids == null) { return null; } const loader = getLoader(args, context, info); if (Array.isArray(type)) { return rejectErrors(ids.map((id) => id == null ? id : loader.load(id))); } return loader.load(ids); } }); }; fieldBuilderProto.loadableList = function loadableList({ load, sort, loaderOptions, resolve, type, byPath, ...options }) { const getLoader = pathDataloaderGetter(loaderOptions, (keys, ctx, args, info) => load(keys, ctx, args, info), undefined, sort, byPath); return this.field({ ...options, type: [ type ], // @ts-expect-error types don't match because this handles both lists and single objects resolve: async (parent, args, context, info) => { const ids = await resolve(parent, args, context, info); const loader = getLoader(args, context, info); return loader.load(ids); } }); }; fieldBuilderProto.loadableGroup = function loadableGroup({ load, group, loaderOptions, byPath, resolve, type, ...options }) { const getLoader = pathDataloaderGetter(loaderOptions, async (keys, ctx, args, info) => { const values = await load(keys, ctx, args, info); const groups = new Map(); for (const value of values) { if (value == null) { continue; } const groupKey = group(value); if (!groups.has(groupKey)) { groups.set(groupKey, []); } groups.get(groupKey).push(value); } return keys.map((key) => { var _groups_get; return (_groups_get = groups.get(key)) !== null && _groups_get !== void 0 ? _groups_get : []; }); }, undefined, false, byPath); return this.field({ ...options, type: [ type ], // @ts-expect-error types don't match because this handles both lists and single objects resolve: async (parent, args, context, info) => { const ids = await resolve(parent, args, context, info); const loader = getLoader(args, context, info); return loader.load(ids); } }); }; //# sourceMappingURL=field-builder.js.map