Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(wrap): New transform AddArgumentsAsVariables #4291

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/spotty-bobcats-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-tools/wrap': minor
---

New transform: AddArgumentsAsVariables
165 changes: 165 additions & 0 deletions packages/wrap/src/transforms/AddArgumentsAsVariables.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import {
ArgumentNode,
DocumentNode,
FragmentDefinitionNode,
GraphQLArgument,
GraphQLField,
GraphQLObjectType,
GraphQLSchema,
Kind,
OperationDefinitionNode,
SelectionNode,
SelectionSetNode,
VariableDefinitionNode,
} from 'graphql';

import { Transform, DelegationContext } from '@graphql-tools/delegate';

import {
ExecutionRequest,
serializeInputValue,
updateArgument,
createVariableNameGenerator,
} from '@graphql-tools/utils';

interface AddArgumentsAsVariablesTransformationContext extends Record<string, any> {}

export default class AddArgumentsAsVariables<TContext = Record<string, any>>
implements Transform<AddArgumentsAsVariablesTransformationContext, TContext>
{
private readonly args: Record<string, any>;

constructor(args: Record<string, any>) {
this.args = Object.entries(args).reduce(
(prev, [key, val]) => ({
...prev,
[key]: val,
}),
{}
);
}

public transformRequest(
originalRequest: ExecutionRequest,
delegationContext: DelegationContext<TContext>,
_transformationContext: AddArgumentsAsVariablesTransformationContext
): ExecutionRequest {
const { document, variables } = addVariablesToRootField(delegationContext.targetSchema, originalRequest, this.args);

return {
...originalRequest,
document,
variables,
};
}
}

function addVariablesToRootField(
targetSchema: GraphQLSchema,
originalRequest: ExecutionRequest,
args: Record<string, any>
): {
document: DocumentNode;
variables: Record<string, any>;
} {
const document = originalRequest.document;
const variableValues = originalRequest.variables ?? {};

const operations: Array<OperationDefinitionNode> = document.definitions.filter(
def => def.kind === Kind.OPERATION_DEFINITION
) as Array<OperationDefinitionNode>;
const fragments: Array<FragmentDefinitionNode> = document.definitions.filter(
def => def.kind === Kind.FRAGMENT_DEFINITION
) as Array<FragmentDefinitionNode>;

const newOperations = operations.map((operation: OperationDefinitionNode) => {
const variableDefinitionMap: Record<string, VariableDefinitionNode> = (operation.variableDefinitions ?? []).reduce(
(prev, def) => ({
...prev,
[def.variable.name.value]: def,
}),
{}
);

let type: GraphQLObjectType | null | undefined;
if (operation.operation === 'subscription') {
type = targetSchema.getSubscriptionType();
} else if (operation.operation === 'mutation') {
type = targetSchema.getMutationType();
} else {
type = targetSchema.getQueryType();
}
const newSelectionSet: Array<SelectionNode> = [];

operation.selectionSet.selections.forEach((selection: SelectionNode) => {
if (selection.kind === Kind.FIELD) {
const argumentNodes = selection.arguments ?? [];
const argumentNodeMap: Record<string, ArgumentNode> = argumentNodes.reduce(
(prev, argument) => ({
...prev,
[argument.name.value]: argument,
}),
{}
);

const targetField = type?.getFields()[selection.name.value];

// excludes __typename
if (targetField != null) {
updateArguments(targetField, argumentNodeMap, variableDefinitionMap, variableValues, args);
}

newSelectionSet.push({
...selection,
arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),
});
} else {
newSelectionSet.push(selection);
}
});

return {
...operation,
variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),
selectionSet: {
kind: Kind.SELECTION_SET,
selections: newSelectionSet,
} as SelectionSetNode,
};
});

return {
document: {
...document,
definitions: [...newOperations, ...fragments],
},
variables: variableValues,
};
}

function updateArguments(
targetField: GraphQLField<any, any>,
argumentNodeMap: Record<string, ArgumentNode>,
variableDefinitionMap: Record<string, VariableDefinitionNode>,
variableValues: Record<string, any>,
newArgs: Record<string, any>
): void {
const generateVariableName = createVariableNameGenerator(variableDefinitionMap);

targetField.args.forEach((argument: GraphQLArgument) => {
const argName = argument.name;
const argType = argument.type;

if (argName in newArgs) {
updateArgument(
argumentNodeMap,
variableDefinitionMap,
variableValues,
argName,
generateVariableName(argName),
argType,
serializeInputValue(argType, newArgs[argName])
);
}
});
}
1 change: 1 addition & 0 deletions packages/wrap/src/transforms/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { default as AddArgumentsAsVariables } from './AddArgumentsAsVariables';
export { default as RenameTypes } from './RenameTypes';
export { default as FilterTypes } from './FilterTypes';
export { default as RenameRootTypes } from './RenameRootTypes';
Expand Down
65 changes: 65 additions & 0 deletions packages/wrap/tests/transformAddArgumentsAsVariables.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { wrapSchema, AddArgumentsAsVariables } from '@graphql-tools/wrap';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { parse, execute } from 'graphql';
import { assertSome } from '@graphql-tools/utils';

describe('AddArgumentsAsVariables', () => {
const schema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
input InputObject {
field1: String
field2: String
}

type OutputObject {
field1: String
field2: String
field3: String
field4: String
}

type Query {
test(argument: InputObject, otherArgument: String, thirdArgument: String): OutputObject
}
`,
resolvers: {
Query: {
test: (_root, args) => {
return { ...args.argument, field3: args.otherArgument, field4: args.thirdArgument };
},
},
},
});

const transformedSchema = wrapSchema({
schema,
transforms: [
new AddArgumentsAsVariables({ argument: { field1: 'field1', field2: 'field2' }, thirdArgument: 'field4' }),
],
});

test('adds provided arguments as variables', async () => {
const query = /* GraphQL */ `
{
test(otherArgument: "field3") {
field1
field2
field3
field4
}
}
`;

const result = await execute({
schema: transformedSchema,
document: parse(query),
});
assertSome(result.data);
expect(result.errors).toBeUndefined();
const dataTest: any = result.data['test'];
expect(dataTest.field1).toBe('field1');
expect(dataTest.field2).toBe('field2');
expect(dataTest.field3).toBe('field3');
expect(dataTest.field4).toBe('field4');
});
});