@graphql-mesh/transport-rest
Version:
64 lines (63 loc) • 2.58 kB
JavaScript
import { dset } from 'dset';
import { stringInterpolator } from '@graphql-mesh/string-interpolation';
import { getDirective } from '@graphql-tools/utils';
export function processLinkFieldAnnotations(field, defaultRootTypeName, defaultFieldName) {
field.resolve = function linkDirectiveHandler(root, args, context, info) {
const linkResolverMap = findLinkResolverMap({
schema: info.schema,
defaultRootTypeName,
defaultFieldName,
parentFieldName: root.$field,
operationType: info.operation.operation,
});
const linkResolverOpts = linkResolverMap[field.name];
return linkResolver(linkResolverOpts, { root, args, context, info, env: process.env });
};
}
function findLinkResolverMap({ schema, operationType, defaultRootTypeName, defaultFieldName, }) {
const parentType = schema.getRootType(operationType);
const parentField = parentType.getFields()[operationType];
if (parentField) {
const linkResolverMap = getLinkResolverMap(schema, parentField);
if (linkResolverMap) {
return linkResolverMap;
}
}
const defaultRootType = schema.getType(defaultRootTypeName);
if (defaultRootType) {
const defaultField = defaultRootType.getFields()[defaultFieldName];
if (defaultField) {
const linkResolverMap = getLinkResolverMap(schema, defaultField);
if (linkResolverMap) {
return linkResolverMap;
}
}
}
}
function getLinkResolverMap(schema, field) {
const parentFieldLinkResolverDirectives = getDirective(schema, field, 'linkResolver');
if (parentFieldLinkResolverDirectives?.length) {
const linkResolverMap = parentFieldLinkResolverDirectives[0].linkResolverMap;
if (linkResolverMap) {
return linkResolverMap;
}
}
}
function linkResolver({ linkObjArgs, targetTypeName, targetFieldName }, { root, args, context, info, env }) {
for (const argKey in linkObjArgs) {
const argInterpolation = linkObjArgs[argKey];
const actualValue = typeof argInterpolation === 'string'
? stringInterpolator.parse(argInterpolation, {
root,
args,
context,
info,
env,
})
: argInterpolation;
dset(args, argKey, actualValue);
}
const type = info.schema.getType(targetTypeName);
const field = type.getFields()[targetFieldName];
return field.resolve(root, args, context, info);
}