Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@graphql-tools/delegate

Package Overview
Dependencies
Maintainers
3
Versions
1810
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@graphql-tools/delegate - npm Package Compare versions

Comparing version 6.0.8-alpha-818e986.0 to 6.0.8-alpha-9f8f3e5.0

delegationBindings.d.ts

2

delegateToSchema.d.ts
import { GraphQLSchema } from 'graphql';
import { IDelegateToSchemaOptions, IDelegateRequestOptions } from './types';
export declare function delegateToSchema(options: IDelegateToSchemaOptions | GraphQLSchema): any;
export declare function delegateRequest({ request, schema: subschemaOrSubschemaConfig, rootValue, info, operation, fieldName, args, returnType, context, transforms, transformedSchema, skipValidation, skipTypeMerging, }: IDelegateRequestOptions): any;
export declare function delegateRequest({ request, schema: subschemaOrSubschemaConfig, rootValue, info, operation, fieldName, args, returnType, context, transforms, transformedSchema, skipValidation, skipTypeMerging, binding, }: IDelegateRequestOptions): any;

@@ -8,2 +8,139 @@ 'use strict';

const OBJECT_SUBSCHEMA_SYMBOL = Symbol('initialSubschema');
const FIELD_SUBSCHEMA_MAP_SYMBOL = Symbol('subschemaMap');
function getSubschema(result, responseKey) {
const subschema = result[FIELD_SUBSCHEMA_MAP_SYMBOL] && result[FIELD_SUBSCHEMA_MAP_SYMBOL][responseKey];
return subschema || result[OBJECT_SUBSCHEMA_SYMBOL];
}
function setObjectSubschema(result, subschema) {
result[OBJECT_SUBSCHEMA_SYMBOL] = subschema;
}
function isSubschemaConfig(value) {
return Boolean(value.schema);
}
function isSubschema(value) {
return Boolean(value.transformedSchema);
}
class Subschema {
constructor(config) {
var _a;
this.schema = config.schema;
this.executor = config.executor;
this.subscriber = config.subscriber;
this.createProxyingResolver = config.createProxyingResolver;
this.transforms = (_a = config.transforms) !== null && _a !== void 0 ? _a : [];
this.merge = config.merge;
this.transformedSchema = utils.applySchemaTransforms(this.schema, this.transforms);
}
}
function getDelegatingOperation(parentType, schema) {
if (parentType === schema.getMutationType()) {
return 'mutation';
}
else if (parentType === schema.getSubscriptionType()) {
return 'subscription';
}
return 'query';
}
function createRequestFromInfo({ info, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, selectionSet, fieldNodes = info.fieldNodes, }) {
return createRequest({
sourceSchema: info.schema,
sourceParentType: info.parentType,
sourceFieldName: info.fieldName,
fragments: info.fragments,
variableDefinitions: info.operation.variableDefinitions,
variableValues: info.variableValues,
targetOperation: operation,
targetFieldName: fieldName,
selectionSet,
fieldNodes,
});
}
function createRequest({ sourceSchema, sourceParentType, sourceFieldName, fragments, variableDefinitions, variableValues, targetOperation, targetFieldName, selectionSet, fieldNodes, }) {
var _a;
let newSelectionSet = selectionSet;
let argumentNodeMap;
if (fieldNodes == null) {
argumentNodeMap = Object.create(null);
}
else {
const selections = fieldNodes.reduce((acc, fieldNode) => (fieldNode.selectionSet != null ? acc.concat(fieldNode.selectionSet.selections) : acc), []);
newSelectionSet = selections.length
? {
kind: graphql.Kind.SELECTION_SET,
selections,
}
: undefined;
argumentNodeMap = {};
const args = (_a = fieldNodes[0]) === null || _a === void 0 ? void 0 : _a.arguments;
if (args) {
argumentNodeMap = args.reduce((prev, curr) => ({
...prev,
[curr.name.value]: curr,
}), argumentNodeMap);
}
}
const newVariables = Object.create(null);
const variableDefinitionMap = Object.create(null);
if (sourceSchema != null && variableDefinitions != null) {
variableDefinitions.forEach(def => {
const varName = def.variable.name.value;
variableDefinitionMap[varName] = def;
const varType = graphql.typeFromAST(sourceSchema, def.type);
const serializedValue = utils.serializeInputValue(varType, variableValues[varName]);
if (serializedValue !== undefined) {
newVariables[varName] = serializedValue;
}
});
}
if (sourceParentType != null) {
updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, newVariables);
}
const rootfieldNode = {
kind: graphql.Kind.FIELD,
arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),
name: {
kind: graphql.Kind.NAME,
value: targetFieldName || fieldNodes[0].name.value,
},
selectionSet: newSelectionSet,
};
const operationDefinition = {
kind: graphql.Kind.OPERATION_DEFINITION,
operation: targetOperation,
variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),
selectionSet: {
kind: graphql.Kind.SELECTION_SET,
selections: [rootfieldNode],
},
};
let definitions = [operationDefinition];
if (fragments != null) {
definitions = definitions.concat(Object.keys(fragments).map(fragmentName => fragments[fragmentName]));
}
const document = {
kind: graphql.Kind.DOCUMENT,
definitions,
};
return {
document,
variables: newVariables,
};
}
function updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, variableValues) {
const sourceField = sourceParentType.getFields()[sourceFieldName];
sourceField.args.forEach((argument) => {
const argName = argument.name;
const sourceArgType = argument.type;
if (argumentNodeMap[argName] === undefined) {
const defaultValue = argument.defaultValue;
if (defaultValue !== undefined) {
utils.updateArgument(argName, sourceArgType, argumentNodeMap, variableDefinitionMap, variableValues, utils.serializeInputValue(sourceArgType, defaultValue));
}
}
});
}
class ExpandAbstractTypes {

@@ -617,13 +754,2 @@ constructor(sourceSchema, targetSchema) {

const OBJECT_SUBSCHEMA_SYMBOL = Symbol('initialSubschema');
const FIELD_SUBSCHEMA_MAP_SYMBOL = Symbol('subschemaMap');
function getSubschema(result, responseKey) {
const subschema = result[FIELD_SUBSCHEMA_MAP_SYMBOL] && result[FIELD_SUBSCHEMA_MAP_SYMBOL][responseKey];
return subschema || result[OBJECT_SUBSCHEMA_SYMBOL];
}
function setObjectSubschema(result, subschema) {
result[OBJECT_SUBSCHEMA_SYMBOL] = subschema;
}
function unwrapResult(parent, path) {

@@ -778,6 +904,2 @@ let newParent = parent;

function isSubschemaConfig(value) {
return Boolean(value.schema);
}
function handleObject(type, object, errors, subschema, context, info, skipTypeMerging) {

@@ -973,109 +1095,68 @@ var _a;

function getDelegatingOperation(parentType, schema) {
if (parentType === schema.getMutationType()) {
return 'mutation';
function defaultDelegationBinding(delegationContext) {
var _a;
const { subschema: schemaOrSubschemaConfig, targetSchema, fieldName, args, context, info, returnType, transforms = [], skipTypeMerging, } = delegationContext;
const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a.stitchingInfo;
let transformedSchema = stitchingInfo === null || stitchingInfo === void 0 ? void 0 : stitchingInfo.transformedSchemas.get(schemaOrSubschemaConfig);
if (transformedSchema != null) {
delegationContext.transformedSchema = transformedSchema;
}
else if (parentType === schema.getSubscriptionType()) {
return 'subscription';
else {
transformedSchema = delegationContext.transformedSchema;
}
return 'query';
}
function createRequestFromInfo({ info, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, selectionSet, fieldNodes = info.fieldNodes, }) {
return createRequest({
sourceSchema: info.schema,
sourceParentType: info.parentType,
sourceFieldName: info.fieldName,
fragments: info.fragments,
variableDefinitions: info.operation.variableDefinitions,
variableValues: info.variableValues,
targetOperation: operation,
targetFieldName: fieldName,
selectionSet,
fieldNodes,
});
}
function createRequest({ sourceSchema, sourceParentType, sourceFieldName, fragments, variableDefinitions, variableValues, targetOperation, targetFieldName, selectionSet, fieldNodes, }) {
var _a;
let newSelectionSet = selectionSet;
let argumentNodeMap;
if (fieldNodes == null) {
argumentNodeMap = Object.create(null);
let delegationTransforms = [
new CheckResultAndHandleErrors(info, fieldName, schemaOrSubschemaConfig, context, returnType, skipTypeMerging),
];
if (stitchingInfo != null) {
delegationTransforms = delegationTransforms.concat([
new AddSelectionSetsByField(info.schema, stitchingInfo.selectionSetsByField),
new AddSelectionSetsByType(info.schema, stitchingInfo.selectionSetsByType),
new WrapConcreteTypes(returnType, transformedSchema),
new ExpandAbstractTypes(info.schema, transformedSchema),
]);
}
else if (info != null) {
delegationTransforms = delegationTransforms.concat([
new WrapConcreteTypes(returnType, transformedSchema),
new ExpandAbstractTypes(info.schema, transformedSchema),
]);
}
else {
const selections = fieldNodes.reduce((acc, fieldNode) => (fieldNode.selectionSet != null ? acc.concat(fieldNode.selectionSet.selections) : acc), []);
newSelectionSet = selections.length
? {
kind: graphql.Kind.SELECTION_SET,
selections,
}
: undefined;
argumentNodeMap = {};
const args = (_a = fieldNodes[0]) === null || _a === void 0 ? void 0 : _a.arguments;
if (args) {
argumentNodeMap = args.reduce((prev, curr) => ({
...prev,
[curr.name.value]: curr,
}), argumentNodeMap);
}
delegationTransforms.push(new WrapConcreteTypes(returnType, transformedSchema));
}
const newVariables = Object.create(null);
const variableDefinitionMap = Object.create(null);
if (sourceSchema != null && variableDefinitions != null) {
variableDefinitions.forEach(def => {
const varName = def.variable.name.value;
variableDefinitionMap[varName] = def;
const varType = graphql.typeFromAST(sourceSchema, def.type);
const serializedValue = utils.serializeInputValue(varType, variableValues[varName]);
if (serializedValue !== undefined) {
newVariables[varName] = serializedValue;
}
});
delegationTransforms = delegationTransforms.concat(transforms.slice().reverse());
if (stitchingInfo != null) {
delegationTransforms.push(new AddFragmentsByField(targetSchema, stitchingInfo.fragmentsByField));
}
if (sourceParentType != null) {
updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, newVariables);
if (args != null) {
delegationTransforms.push(new AddArgumentsAsVariables(targetSchema, args));
}
const rootfieldNode = {
kind: graphql.Kind.FIELD,
arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),
name: {
kind: graphql.Kind.NAME,
value: targetFieldName || fieldNodes[0].name.value,
},
selectionSet: newSelectionSet,
};
const operationDefinition = {
kind: graphql.Kind.OPERATION_DEFINITION,
operation: targetOperation,
variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),
selectionSet: {
kind: graphql.Kind.SELECTION_SET,
selections: [rootfieldNode],
},
};
let definitions = [operationDefinition];
if (fragments != null) {
definitions = definitions.concat(Object.keys(fragments).map(fragmentName => fragments[fragmentName]));
delegationTransforms = delegationTransforms.concat([
new FilterToSchema(targetSchema),
new AddTypenameToAbstract(targetSchema),
]);
return delegationTransforms;
}
class Transformer {
constructor(context, binding = defaultDelegationBinding) {
this.transformations = [];
this.delegationContext = context;
const delegationTransforms = binding(this.delegationContext);
delegationTransforms.forEach(transform => this.addTransform(transform, {}));
}
const document = {
kind: graphql.Kind.DOCUMENT,
definitions,
};
return {
document,
variables: newVariables,
};
addTransform(transform, context = {}) {
this.transformations.push({ transform, context });
}
transformRequest(originalRequest) {
return this.transformations.reduce((request, transformation) => transformation.transform.transformRequest != null
? transformation.transform.transformRequest(request, this.delegationContext, transformation.context)
: request, originalRequest);
}
transformResult(originalResult) {
return this.transformations.reduceRight((result, transformation) => transformation.transform.transformResult != null
? transformation.transform.transformResult(result, this.delegationContext, transformation.context)
: result, originalResult);
}
}
function updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, variableValues) {
const sourceField = sourceParentType.getFields()[sourceFieldName];
sourceField.args.forEach((argument) => {
const argName = argument.name;
const sourceArgType = argument.type;
if (argumentNodeMap[argName] === undefined) {
const defaultValue = argument.defaultValue;
if (defaultValue !== undefined) {
utils.updateArgument(argName, sourceArgType, argumentNodeMap, variableDefinitionMap, variableValues, utils.serializeInputValue(sourceArgType, defaultValue));
}
}
});
}

@@ -1102,6 +1183,3 @@ function delegateToSchema(options) {

}
function getDelegationReturnType(info, targetSchema, operation, fieldName) {
if (info != null) {
return info.returnType;
}
function getDelegationReturnType(targetSchema, operation, fieldName) {
let rootType;

@@ -1119,29 +1197,4 @@ if (operation === 'query') {

}
function buildDelegationTransforms(subschemaOrSubschemaConfig, info, context, targetSchema, fieldName, args, returnType, transforms, transformedSchema, skipTypeMerging) {
function delegateRequest({ request, schema: subschemaOrSubschemaConfig, rootValue, info, operation, fieldName, args, returnType, context, transforms = [], transformedSchema, skipValidation, skipTypeMerging, binding, }) {
var _a, _b;
const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a.stitchingInfo;
let delegationTransforms = [
new CheckResultAndHandleErrors(info, fieldName, subschemaOrSubschemaConfig, context, returnType, skipTypeMerging),
];
if (stitchingInfo != null) {
delegationTransforms.push(new AddSelectionSetsByField(info.schema, stitchingInfo.selectionSetsByField), new AddSelectionSetsByType(info.schema, stitchingInfo.selectionSetsByType));
}
const transformedTargetSchema = stitchingInfo == null
? transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : targetSchema : (_b = transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : stitchingInfo.transformedSchemas.get(subschemaOrSubschemaConfig)) !== null && _b !== void 0 ? _b : targetSchema;
delegationTransforms.push(new WrapConcreteTypes(returnType, transformedTargetSchema));
if (info != null) {
delegationTransforms.push(new ExpandAbstractTypes(info.schema, transformedTargetSchema));
}
delegationTransforms = delegationTransforms.concat(transforms);
if (stitchingInfo != null) {
delegationTransforms.push(new AddFragmentsByField(targetSchema, stitchingInfo.fragmentsByField));
}
if (args != null) {
delegationTransforms.push(new AddArgumentsAsVariables(targetSchema, args));
}
delegationTransforms.push(new FilterToSchema(targetSchema), new AddTypenameToAbstract(targetSchema));
return delegationTransforms;
}
function delegateRequest({ request, schema: subschemaOrSubschemaConfig, rootValue, info, operation, fieldName, args, returnType, context, transforms = [], transformedSchema, skipValidation, skipTypeMerging, }) {
var _a;
let operationDefinition;

@@ -1166,4 +1219,4 @@ let targetOperation;

let targetRootValue;
let requestTransforms = transforms.slice();
let subschemaConfig;
let allTransforms;
if (isSubschemaConfig(subschemaOrSubschemaConfig)) {

@@ -1173,5 +1226,6 @@ subschemaConfig = subschemaOrSubschemaConfig;

targetRootValue = (_a = rootValue !== null && rootValue !== void 0 ? rootValue : subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.rootValue) !== null && _a !== void 0 ? _a : info === null || info === void 0 ? void 0 : info.rootValue;
if (subschemaConfig.transforms != null) {
requestTransforms = requestTransforms.concat(subschemaConfig.transforms);
}
allTransforms =
subschemaOrSubschemaConfig.transforms != null
? subschemaOrSubschemaConfig.transforms.concat(transforms)
: transforms;
}

@@ -1181,15 +1235,21 @@ else {

targetRootValue = rootValue !== null && rootValue !== void 0 ? rootValue : info === null || info === void 0 ? void 0 : info.rootValue;
allTransforms = transforms;
}
const delegationTransforms = buildDelegationTransforms(subschemaOrSubschemaConfig, info, context, targetSchema, targetFieldName, args, returnType !== null && returnType !== void 0 ? returnType : getDelegationReturnType(info, targetSchema, targetOperation, targetFieldName), requestTransforms.reverse(), transformedSchema, skipTypeMerging);
const processedRequest = utils.applyRequestTransforms(request, delegationTransforms);
const delegationContext = {
subschema: subschemaOrSubschemaConfig,
targetSchema,
operation: targetOperation,
fieldName: targetFieldName,
args,
context,
info,
returnType: (_b = returnType !== null && returnType !== void 0 ? returnType : info === null || info === void 0 ? void 0 : info.returnType) !== null && _b !== void 0 ? _b : getDelegationReturnType(targetSchema, targetOperation, targetFieldName),
transforms: allTransforms,
transformedSchema: transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : targetSchema,
skipTypeMerging,
};
const transformer = new Transformer(delegationContext, binding);
const processedRequest = transformer.transformRequest(request);
if (!skipValidation) {
const errors = graphql.validate(targetSchema, processedRequest.document);
if (errors.length > 0) {
if (errors.length > 1) {
const combinedError = new utils.CombinedError(errors);
throw combinedError;
}
const error = errors[0];
throw error.originalError || error;
}
validateRequest(targetSchema, processedRequest.document);
}

@@ -1205,5 +1265,5 @@ if (targetOperation === 'query' || targetOperation === 'mutation') {

if (executionResult instanceof Promise) {
return executionResult.then((originalResult) => utils.applyResultTransforms(originalResult, delegationTransforms));
return executionResult.then(originalResult => transformer.transformResult(originalResult));
}
return utils.applyResultTransforms(executionResult, delegationTransforms);
return transformer.transformResult(executionResult);
}

@@ -1219,14 +1279,20 @@ const subscriber = (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.subscriber) || createDefaultSubscriber(targetSchema, (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.rootValue) || targetRootValue);

// "subscribe" to the subscription result and map the result through the transforms
return utils.mapAsyncIterator(subscriptionResult, result => {
const transformedResult = utils.applyResultTransforms(result, delegationTransforms);
// wrap with fieldName to return for an additional round of resolutioon
// with payload as rootValue
return {
[targetFieldName]: transformedResult,
};
});
return utils.mapAsyncIterator(subscriptionResult, originalResult => ({
[targetFieldName]: transformer.transformResult(originalResult),
}));
}
return utils.applyResultTransforms(subscriptionResult, delegationTransforms);
return transformer.transformResult(subscriptionResult);
});
}
function validateRequest(targetSchema, document) {
const errors = graphql.validate(targetSchema, document);
if (errors.length > 0) {
if (errors.length > 1) {
const combinedError = new utils.CombinedError(errors);
throw combinedError;
}
const error = errors[0];
throw error.originalError || error;
}
}
function createDefaultExecutor(schema, rootValue) {

@@ -1373,2 +1439,3 @@ return ({ document, context, variables, info }) => graphql.execute({

exports.ReplaceFieldWithFragment = ReplaceFieldWithFragment;
exports.Subschema = Subschema;
exports.checkResultAndHandleErrors = checkResultAndHandleErrors;

@@ -1378,2 +1445,3 @@ exports.createMergedResolver = createMergedResolver;

exports.createRequestFromInfo = createRequestFromInfo;
exports.defaultDelegationBinding = defaultDelegationBinding;
exports.defaultMergedResolver = defaultMergedResolver;

@@ -1384,3 +1452,4 @@ exports.delegateRequest = delegateRequest;

exports.handleResult = handleResult;
exports.isSubschema = isSubschema;
exports.isSubschemaConfig = isSubschemaConfig;
//# sourceMappingURL=index.cjs.js.map

@@ -6,4 +6,5 @@ export { delegateToSchema, delegateRequest } from './delegateToSchema';

export { handleResult } from './results/handleResult';
export { getSubschema } from './subschema';
export { Subschema, isSubschema, isSubschemaConfig, getSubschema } from './Subschema';
export * from './delegationBindings';
export * from './transforms';
export * from './types';

@@ -1,4 +0,141 @@

import { visit, visitWithTypeInfo, Kind, getNamedType, isAbstractType, TypeInfo, isObjectType, isInterfaceType, TypeNameMetaFieldDef, getNullableType, isLeafType, isCompositeType, isListType, typeFromAST, isSchema, getOperationAST, validate, execute, subscribe, defaultFieldResolver, parse } from 'graphql';
import { implementsAbstractType, CombinedError, relocatedError, getErrorsByPathSegment, ERROR_SYMBOL, mergeDeep, getErrors, setErrors, slicedError, collectFields, getResponseKeyFromInfo, updateArgument, serializeInputValue, applyRequestTransforms, applyResultTransforms, mapAsyncIterator, concatInlineFragments } from '@graphql-tools/utils';
import { Kind, typeFromAST, visit, visitWithTypeInfo, getNamedType, isAbstractType, TypeInfo, isObjectType, isInterfaceType, TypeNameMetaFieldDef, getNullableType, isLeafType, isCompositeType, isListType, isSchema, getOperationAST, execute, subscribe, validate, defaultFieldResolver, parse } from 'graphql';
import { applySchemaTransforms, serializeInputValue, updateArgument, implementsAbstractType, CombinedError, relocatedError, getErrorsByPathSegment, ERROR_SYMBOL, mergeDeep, getErrors, setErrors, slicedError, collectFields, getResponseKeyFromInfo, mapAsyncIterator, concatInlineFragments } from '@graphql-tools/utils';
const OBJECT_SUBSCHEMA_SYMBOL = Symbol('initialSubschema');
const FIELD_SUBSCHEMA_MAP_SYMBOL = Symbol('subschemaMap');
function getSubschema(result, responseKey) {
const subschema = result[FIELD_SUBSCHEMA_MAP_SYMBOL] && result[FIELD_SUBSCHEMA_MAP_SYMBOL][responseKey];
return subschema || result[OBJECT_SUBSCHEMA_SYMBOL];
}
function setObjectSubschema(result, subschema) {
result[OBJECT_SUBSCHEMA_SYMBOL] = subschema;
}
function isSubschemaConfig(value) {
return Boolean(value.schema);
}
function isSubschema(value) {
return Boolean(value.transformedSchema);
}
class Subschema {
constructor(config) {
var _a;
this.schema = config.schema;
this.executor = config.executor;
this.subscriber = config.subscriber;
this.createProxyingResolver = config.createProxyingResolver;
this.transforms = (_a = config.transforms) !== null && _a !== void 0 ? _a : [];
this.merge = config.merge;
this.transformedSchema = applySchemaTransforms(this.schema, this.transforms);
}
}
function getDelegatingOperation(parentType, schema) {
if (parentType === schema.getMutationType()) {
return 'mutation';
}
else if (parentType === schema.getSubscriptionType()) {
return 'subscription';
}
return 'query';
}
function createRequestFromInfo({ info, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, selectionSet, fieldNodes = info.fieldNodes, }) {
return createRequest({
sourceSchema: info.schema,
sourceParentType: info.parentType,
sourceFieldName: info.fieldName,
fragments: info.fragments,
variableDefinitions: info.operation.variableDefinitions,
variableValues: info.variableValues,
targetOperation: operation,
targetFieldName: fieldName,
selectionSet,
fieldNodes,
});
}
function createRequest({ sourceSchema, sourceParentType, sourceFieldName, fragments, variableDefinitions, variableValues, targetOperation, targetFieldName, selectionSet, fieldNodes, }) {
var _a;
let newSelectionSet = selectionSet;
let argumentNodeMap;
if (fieldNodes == null) {
argumentNodeMap = Object.create(null);
}
else {
const selections = fieldNodes.reduce((acc, fieldNode) => (fieldNode.selectionSet != null ? acc.concat(fieldNode.selectionSet.selections) : acc), []);
newSelectionSet = selections.length
? {
kind: Kind.SELECTION_SET,
selections,
}
: undefined;
argumentNodeMap = {};
const args = (_a = fieldNodes[0]) === null || _a === void 0 ? void 0 : _a.arguments;
if (args) {
argumentNodeMap = args.reduce((prev, curr) => ({
...prev,
[curr.name.value]: curr,
}), argumentNodeMap);
}
}
const newVariables = Object.create(null);
const variableDefinitionMap = Object.create(null);
if (sourceSchema != null && variableDefinitions != null) {
variableDefinitions.forEach(def => {
const varName = def.variable.name.value;
variableDefinitionMap[varName] = def;
const varType = typeFromAST(sourceSchema, def.type);
const serializedValue = serializeInputValue(varType, variableValues[varName]);
if (serializedValue !== undefined) {
newVariables[varName] = serializedValue;
}
});
}
if (sourceParentType != null) {
updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, newVariables);
}
const rootfieldNode = {
kind: Kind.FIELD,
arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),
name: {
kind: Kind.NAME,
value: targetFieldName || fieldNodes[0].name.value,
},
selectionSet: newSelectionSet,
};
const operationDefinition = {
kind: Kind.OPERATION_DEFINITION,
operation: targetOperation,
variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),
selectionSet: {
kind: Kind.SELECTION_SET,
selections: [rootfieldNode],
},
};
let definitions = [operationDefinition];
if (fragments != null) {
definitions = definitions.concat(Object.keys(fragments).map(fragmentName => fragments[fragmentName]));
}
const document = {
kind: Kind.DOCUMENT,
definitions,
};
return {
document,
variables: newVariables,
};
}
function updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, variableValues) {
const sourceField = sourceParentType.getFields()[sourceFieldName];
sourceField.args.forEach((argument) => {
const argName = argument.name;
const sourceArgType = argument.type;
if (argumentNodeMap[argName] === undefined) {
const defaultValue = argument.defaultValue;
if (defaultValue !== undefined) {
updateArgument(argName, sourceArgType, argumentNodeMap, variableDefinitionMap, variableValues, serializeInputValue(sourceArgType, defaultValue));
}
}
});
}
class ExpandAbstractTypes {

@@ -612,13 +749,2 @@ constructor(sourceSchema, targetSchema) {

const OBJECT_SUBSCHEMA_SYMBOL = Symbol('initialSubschema');
const FIELD_SUBSCHEMA_MAP_SYMBOL = Symbol('subschemaMap');
function getSubschema(result, responseKey) {
const subschema = result[FIELD_SUBSCHEMA_MAP_SYMBOL] && result[FIELD_SUBSCHEMA_MAP_SYMBOL][responseKey];
return subschema || result[OBJECT_SUBSCHEMA_SYMBOL];
}
function setObjectSubschema(result, subschema) {
result[OBJECT_SUBSCHEMA_SYMBOL] = subschema;
}
function unwrapResult(parent, path) {

@@ -773,6 +899,2 @@ let newParent = parent;

function isSubschemaConfig(value) {
return Boolean(value.schema);
}
function handleObject(type, object, errors, subschema, context, info, skipTypeMerging) {

@@ -968,109 +1090,68 @@ var _a;

function getDelegatingOperation(parentType, schema) {
if (parentType === schema.getMutationType()) {
return 'mutation';
function defaultDelegationBinding(delegationContext) {
var _a;
const { subschema: schemaOrSubschemaConfig, targetSchema, fieldName, args, context, info, returnType, transforms = [], skipTypeMerging, } = delegationContext;
const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a.stitchingInfo;
let transformedSchema = stitchingInfo === null || stitchingInfo === void 0 ? void 0 : stitchingInfo.transformedSchemas.get(schemaOrSubschemaConfig);
if (transformedSchema != null) {
delegationContext.transformedSchema = transformedSchema;
}
else if (parentType === schema.getSubscriptionType()) {
return 'subscription';
else {
transformedSchema = delegationContext.transformedSchema;
}
return 'query';
}
function createRequestFromInfo({ info, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, selectionSet, fieldNodes = info.fieldNodes, }) {
return createRequest({
sourceSchema: info.schema,
sourceParentType: info.parentType,
sourceFieldName: info.fieldName,
fragments: info.fragments,
variableDefinitions: info.operation.variableDefinitions,
variableValues: info.variableValues,
targetOperation: operation,
targetFieldName: fieldName,
selectionSet,
fieldNodes,
});
}
function createRequest({ sourceSchema, sourceParentType, sourceFieldName, fragments, variableDefinitions, variableValues, targetOperation, targetFieldName, selectionSet, fieldNodes, }) {
var _a;
let newSelectionSet = selectionSet;
let argumentNodeMap;
if (fieldNodes == null) {
argumentNodeMap = Object.create(null);
let delegationTransforms = [
new CheckResultAndHandleErrors(info, fieldName, schemaOrSubschemaConfig, context, returnType, skipTypeMerging),
];
if (stitchingInfo != null) {
delegationTransforms = delegationTransforms.concat([
new AddSelectionSetsByField(info.schema, stitchingInfo.selectionSetsByField),
new AddSelectionSetsByType(info.schema, stitchingInfo.selectionSetsByType),
new WrapConcreteTypes(returnType, transformedSchema),
new ExpandAbstractTypes(info.schema, transformedSchema),
]);
}
else if (info != null) {
delegationTransforms = delegationTransforms.concat([
new WrapConcreteTypes(returnType, transformedSchema),
new ExpandAbstractTypes(info.schema, transformedSchema),
]);
}
else {
const selections = fieldNodes.reduce((acc, fieldNode) => (fieldNode.selectionSet != null ? acc.concat(fieldNode.selectionSet.selections) : acc), []);
newSelectionSet = selections.length
? {
kind: Kind.SELECTION_SET,
selections,
}
: undefined;
argumentNodeMap = {};
const args = (_a = fieldNodes[0]) === null || _a === void 0 ? void 0 : _a.arguments;
if (args) {
argumentNodeMap = args.reduce((prev, curr) => ({
...prev,
[curr.name.value]: curr,
}), argumentNodeMap);
}
delegationTransforms.push(new WrapConcreteTypes(returnType, transformedSchema));
}
const newVariables = Object.create(null);
const variableDefinitionMap = Object.create(null);
if (sourceSchema != null && variableDefinitions != null) {
variableDefinitions.forEach(def => {
const varName = def.variable.name.value;
variableDefinitionMap[varName] = def;
const varType = typeFromAST(sourceSchema, def.type);
const serializedValue = serializeInputValue(varType, variableValues[varName]);
if (serializedValue !== undefined) {
newVariables[varName] = serializedValue;
}
});
delegationTransforms = delegationTransforms.concat(transforms.slice().reverse());
if (stitchingInfo != null) {
delegationTransforms.push(new AddFragmentsByField(targetSchema, stitchingInfo.fragmentsByField));
}
if (sourceParentType != null) {
updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, newVariables);
if (args != null) {
delegationTransforms.push(new AddArgumentsAsVariables(targetSchema, args));
}
const rootfieldNode = {
kind: Kind.FIELD,
arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),
name: {
kind: Kind.NAME,
value: targetFieldName || fieldNodes[0].name.value,
},
selectionSet: newSelectionSet,
};
const operationDefinition = {
kind: Kind.OPERATION_DEFINITION,
operation: targetOperation,
variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),
selectionSet: {
kind: Kind.SELECTION_SET,
selections: [rootfieldNode],
},
};
let definitions = [operationDefinition];
if (fragments != null) {
definitions = definitions.concat(Object.keys(fragments).map(fragmentName => fragments[fragmentName]));
delegationTransforms = delegationTransforms.concat([
new FilterToSchema(targetSchema),
new AddTypenameToAbstract(targetSchema),
]);
return delegationTransforms;
}
class Transformer {
constructor(context, binding = defaultDelegationBinding) {
this.transformations = [];
this.delegationContext = context;
const delegationTransforms = binding(this.delegationContext);
delegationTransforms.forEach(transform => this.addTransform(transform, {}));
}
const document = {
kind: Kind.DOCUMENT,
definitions,
};
return {
document,
variables: newVariables,
};
addTransform(transform, context = {}) {
this.transformations.push({ transform, context });
}
transformRequest(originalRequest) {
return this.transformations.reduce((request, transformation) => transformation.transform.transformRequest != null
? transformation.transform.transformRequest(request, this.delegationContext, transformation.context)
: request, originalRequest);
}
transformResult(originalResult) {
return this.transformations.reduceRight((result, transformation) => transformation.transform.transformResult != null
? transformation.transform.transformResult(result, this.delegationContext, transformation.context)
: result, originalResult);
}
}
function updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, variableValues) {
const sourceField = sourceParentType.getFields()[sourceFieldName];
sourceField.args.forEach((argument) => {
const argName = argument.name;
const sourceArgType = argument.type;
if (argumentNodeMap[argName] === undefined) {
const defaultValue = argument.defaultValue;
if (defaultValue !== undefined) {
updateArgument(argName, sourceArgType, argumentNodeMap, variableDefinitionMap, variableValues, serializeInputValue(sourceArgType, defaultValue));
}
}
});
}

@@ -1097,6 +1178,3 @@ function delegateToSchema(options) {

}
function getDelegationReturnType(info, targetSchema, operation, fieldName) {
if (info != null) {
return info.returnType;
}
function getDelegationReturnType(targetSchema, operation, fieldName) {
let rootType;

@@ -1114,29 +1192,4 @@ if (operation === 'query') {

}
function buildDelegationTransforms(subschemaOrSubschemaConfig, info, context, targetSchema, fieldName, args, returnType, transforms, transformedSchema, skipTypeMerging) {
function delegateRequest({ request, schema: subschemaOrSubschemaConfig, rootValue, info, operation, fieldName, args, returnType, context, transforms = [], transformedSchema, skipValidation, skipTypeMerging, binding, }) {
var _a, _b;
const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a.stitchingInfo;
let delegationTransforms = [
new CheckResultAndHandleErrors(info, fieldName, subschemaOrSubschemaConfig, context, returnType, skipTypeMerging),
];
if (stitchingInfo != null) {
delegationTransforms.push(new AddSelectionSetsByField(info.schema, stitchingInfo.selectionSetsByField), new AddSelectionSetsByType(info.schema, stitchingInfo.selectionSetsByType));
}
const transformedTargetSchema = stitchingInfo == null
? transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : targetSchema : (_b = transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : stitchingInfo.transformedSchemas.get(subschemaOrSubschemaConfig)) !== null && _b !== void 0 ? _b : targetSchema;
delegationTransforms.push(new WrapConcreteTypes(returnType, transformedTargetSchema));
if (info != null) {
delegationTransforms.push(new ExpandAbstractTypes(info.schema, transformedTargetSchema));
}
delegationTransforms = delegationTransforms.concat(transforms);
if (stitchingInfo != null) {
delegationTransforms.push(new AddFragmentsByField(targetSchema, stitchingInfo.fragmentsByField));
}
if (args != null) {
delegationTransforms.push(new AddArgumentsAsVariables(targetSchema, args));
}
delegationTransforms.push(new FilterToSchema(targetSchema), new AddTypenameToAbstract(targetSchema));
return delegationTransforms;
}
function delegateRequest({ request, schema: subschemaOrSubschemaConfig, rootValue, info, operation, fieldName, args, returnType, context, transforms = [], transformedSchema, skipValidation, skipTypeMerging, }) {
var _a;
let operationDefinition;

@@ -1161,4 +1214,4 @@ let targetOperation;

let targetRootValue;
let requestTransforms = transforms.slice();
let subschemaConfig;
let allTransforms;
if (isSubschemaConfig(subschemaOrSubschemaConfig)) {

@@ -1168,5 +1221,6 @@ subschemaConfig = subschemaOrSubschemaConfig;

targetRootValue = (_a = rootValue !== null && rootValue !== void 0 ? rootValue : subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.rootValue) !== null && _a !== void 0 ? _a : info === null || info === void 0 ? void 0 : info.rootValue;
if (subschemaConfig.transforms != null) {
requestTransforms = requestTransforms.concat(subschemaConfig.transforms);
}
allTransforms =
subschemaOrSubschemaConfig.transforms != null
? subschemaOrSubschemaConfig.transforms.concat(transforms)
: transforms;
}

@@ -1176,15 +1230,21 @@ else {

targetRootValue = rootValue !== null && rootValue !== void 0 ? rootValue : info === null || info === void 0 ? void 0 : info.rootValue;
allTransforms = transforms;
}
const delegationTransforms = buildDelegationTransforms(subschemaOrSubschemaConfig, info, context, targetSchema, targetFieldName, args, returnType !== null && returnType !== void 0 ? returnType : getDelegationReturnType(info, targetSchema, targetOperation, targetFieldName), requestTransforms.reverse(), transformedSchema, skipTypeMerging);
const processedRequest = applyRequestTransforms(request, delegationTransforms);
const delegationContext = {
subschema: subschemaOrSubschemaConfig,
targetSchema,
operation: targetOperation,
fieldName: targetFieldName,
args,
context,
info,
returnType: (_b = returnType !== null && returnType !== void 0 ? returnType : info === null || info === void 0 ? void 0 : info.returnType) !== null && _b !== void 0 ? _b : getDelegationReturnType(targetSchema, targetOperation, targetFieldName),
transforms: allTransforms,
transformedSchema: transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : targetSchema,
skipTypeMerging,
};
const transformer = new Transformer(delegationContext, binding);
const processedRequest = transformer.transformRequest(request);
if (!skipValidation) {
const errors = validate(targetSchema, processedRequest.document);
if (errors.length > 0) {
if (errors.length > 1) {
const combinedError = new CombinedError(errors);
throw combinedError;
}
const error = errors[0];
throw error.originalError || error;
}
validateRequest(targetSchema, processedRequest.document);
}

@@ -1200,5 +1260,5 @@ if (targetOperation === 'query' || targetOperation === 'mutation') {

if (executionResult instanceof Promise) {
return executionResult.then((originalResult) => applyResultTransforms(originalResult, delegationTransforms));
return executionResult.then(originalResult => transformer.transformResult(originalResult));
}
return applyResultTransforms(executionResult, delegationTransforms);
return transformer.transformResult(executionResult);
}

@@ -1214,14 +1274,20 @@ const subscriber = (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.subscriber) || createDefaultSubscriber(targetSchema, (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.rootValue) || targetRootValue);

// "subscribe" to the subscription result and map the result through the transforms
return mapAsyncIterator(subscriptionResult, result => {
const transformedResult = applyResultTransforms(result, delegationTransforms);
// wrap with fieldName to return for an additional round of resolutioon
// with payload as rootValue
return {
[targetFieldName]: transformedResult,
};
});
return mapAsyncIterator(subscriptionResult, originalResult => ({
[targetFieldName]: transformer.transformResult(originalResult),
}));
}
return applyResultTransforms(subscriptionResult, delegationTransforms);
return transformer.transformResult(subscriptionResult);
});
}
function validateRequest(targetSchema, document) {
const errors = validate(targetSchema, document);
if (errors.length > 0) {
if (errors.length > 1) {
const combinedError = new CombinedError(errors);
throw combinedError;
}
const error = errors[0];
throw error.originalError || error;
}
}
function createDefaultExecutor(schema, rootValue) {

@@ -1359,3 +1425,3 @@ return ({ document, context, variables, info }) => execute({

export { AddArgumentsAsVariables, AddFragmentsByField, AddSelectionSetsByType as AddMergedTypeSelectionSets, AddSelectionSetsByField, AddTypenameToAbstract, CheckResultAndHandleErrors, ExpandAbstractTypes, FilterToSchema, ReplaceFieldWithFragment, checkResultAndHandleErrors, createMergedResolver, createRequest, createRequestFromInfo, defaultMergedResolver, delegateRequest, delegateToSchema, getSubschema, handleResult, isSubschemaConfig };
export { AddArgumentsAsVariables, AddFragmentsByField, AddSelectionSetsByType as AddMergedTypeSelectionSets, AddSelectionSetsByField, AddTypenameToAbstract, CheckResultAndHandleErrors, ExpandAbstractTypes, FilterToSchema, ReplaceFieldWithFragment, Subschema, checkResultAndHandleErrors, createMergedResolver, createRequest, createRequestFromInfo, defaultDelegationBinding, defaultMergedResolver, delegateRequest, delegateToSchema, getSubschema, handleResult, isSubschema, isSubschemaConfig };
//# sourceMappingURL=index.esm.js.map
{
"name": "@graphql-tools/delegate",
"version": "6.0.8-alpha-818e986.0",
"version": "6.0.8-alpha-9f8f3e5.0",
"description": "A set of utils for faster development of GraphQL tools",

@@ -10,4 +10,4 @@ "sideEffects": false,

"dependencies": {
"@graphql-tools/schema": "6.0.8-alpha-818e986.0",
"@graphql-tools/utils": "6.0.8-alpha-818e986.0",
"@graphql-tools/schema": "6.0.8-alpha-9f8f3e5.0",
"@graphql-tools/utils": "6.0.8-alpha-9f8f3e5.0",
"tslib": "~2.0.0"

@@ -14,0 +14,0 @@ },

@@ -1,5 +0,20 @@

import { GraphQLSchema, GraphQLOutputType, SelectionSetNode, FieldNode, DocumentNode, GraphQLResolveInfo, GraphQLFieldResolver, InlineFragmentNode, FragmentDefinitionNode, GraphQLObjectType, VariableDefinitionNode } from 'graphql';
import { GraphQLSchema, GraphQLOutputType, SelectionSetNode, FieldNode, DocumentNode, GraphQLResolveInfo, GraphQLFieldResolver, InlineFragmentNode, FragmentDefinitionNode, GraphQLObjectType, VariableDefinitionNode, OperationTypeNode } from 'graphql';
import { Operation, Transform, Request, TypeMap, ExecutionResult } from '@graphql-tools/utils';
import { Subschema } from './Subschema';
export interface DelegationContext {
subschema: GraphQLSchema | SubschemaConfig;
targetSchema: GraphQLSchema;
operation: OperationTypeNode;
fieldName: string;
args: Record<string, any>;
context: Record<string, any>;
info: GraphQLResolveInfo;
returnType: GraphQLOutputType;
transforms: Array<Transform>;
transformedSchema: GraphQLSchema;
skipTypeMerging: boolean;
}
export declare type DelegationBinding = (delegationContext: DelegationContext) => Array<Transform>;
export interface IDelegateToSchemaOptions<TContext = Record<string, any>, TArgs = Record<string, any>> {
schema: GraphQLSchema | SubschemaConfig;
schema: GraphQLSchema | SubschemaConfig | Subschema;
operation?: Operation;

@@ -18,2 +33,3 @@ fieldName?: string;

skipTypeMerging?: boolean;
binding?: DelegationBinding;
}

@@ -86,3 +102,2 @@ export interface IDelegateRequestOptions extends Omit<IDelegateToSchemaOptions, 'info'> {

export declare type MergedTypeResolver = (originalResult: any, context: Record<string, any>, info: GraphQLResolveInfo, subschema: GraphQLSchema | SubschemaConfig, selectionSet: SelectionSetNode) => any;
export declare function isSubschemaConfig(value: any): value is SubschemaConfig;
export interface StitchingInfo {

@@ -89,0 +104,0 @@ transformedSchemas: Map<GraphQLSchema | SubschemaConfig, GraphQLSchema>;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc