Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "Delay variable coercion until argument use.",
"packageName": "@graphitation/supermassive",
"email": "vrazuvaev@microsoft.com_msteamsmdb",
"dependentChangeType": "patch"
}
186 changes: 186 additions & 0 deletions packages/supermassive/src/__tests__/execute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {
execute as graphQLExecute,
subscribe as graphQLSubscribe,
GraphQLSchema,
GraphQLScalarType,
Kind,
} from "graphql";
import { makeSchema } from "../benchmarks/swapi-schema";
import models from "../benchmarks/swapi-schema/models";
Expand Down Expand Up @@ -677,4 +679,188 @@ describe("executeWithoutSchema - regression tests", () => {
const events = await drainExecution(result);
expect(events).toMatchSnapshot();
});

test("coerces input variables after loading the root field schema fragment", async () => {
expect.assertions(3);

let resolvedArgs: unknown;
const loaderRequests: string[] = [];

const result = await executeWithoutSchema({
document: parse(`
mutation useReorderConversationFoldersMutation(
$input: OneGQL_ReorderConversationFoldersInput!
) {
reorderConversationFolders(input: $input)
}
`),
variableValues: {
input: {
ids: ["folder-1"],
},
},
schemaFragment: {
schemaId: "test",
definitions: { types: {} },
resolvers: {
Mutation: {
reorderConversationFolders(
_source: unknown,
args: { input: { ids: string[] } },
) {
resolvedArgs = args;
return args.input.ids[0];
},
},
},
},
schemaFragmentLoader: (currentFragment, _context, req) => {
if (req.kind !== "ReturnType") {
throw new Error(`Unexpected schema fragment request: ${req.kind}`);
}
loaderRequests.push(
`${req.kind}:${req.parentTypeName}.${req.fieldName}`,
);
currentFragment.definitions = encodeASTSchema(
parse(`
type Mutation {
reorderConversationFolders(input: OneGQL_ReorderConversationFoldersInput!): ID!
}

input OneGQL_ReorderConversationFoldersInput {
ids: [ID!]!
folderId: ID = "default-folder"
}
`),
)[0];
return Promise.resolve({ mergedFragment: currentFragment });
},
});

expect(await drainExecution(result)).toEqual({
data: {
reorderConversationFolders: "folder-1",
},
});
expect(resolvedArgs).toEqual({
input: {
ids: ["folder-1"],
folderId: "default-folder",
},
});
expect(loaderRequests).toEqual([
"ReturnType:Mutation.reorderConversationFolders",
]);
});

test("does not load schema fragments for unused input variable definitions", async () => {
expect.assertions(2);

const result = await executeWithoutSchema({
document: parse(`
mutation WithUnusedInput($input: MissingInput) {
ping
}
`),
variableValues: {
input: {
id: "unused",
},
},
schemaFragment: {
schemaId: "test",
definitions: { types: {} },
resolvers: {
Mutation: {
ping() {
return "pong";
},
},
},
},
schemaFragmentLoader: (currentFragment, _context, req) => {
expect(req).toMatchObject({
kind: "ReturnType",
parentTypeName: "Mutation",
fieldName: "ping",
});
currentFragment.definitions = encodeASTSchema(
parse(`
type Mutation {
ping: String!
}
`),
)[0];
return Promise.resolve({ mergedFragment: currentFragment });
},
});

expect(await drainExecution(result)).toEqual({ data: { ping: "pong" } });
});

test("coerces a used variable only once", async () => {
expect.assertions(3);

let parseValueCalls = 0;
const argsAtResolver: unknown[] = [];
const CountedScalar = new GraphQLScalarType({
name: "CountedScalar",
serialize(value) {
return value;
},
parseValue(value) {
parseValueCalls++;
return `coerced:${value}`;
},
parseLiteral(node) {
return node.kind === Kind.STRING ? `literal:${node.value}` : undefined;
},
});
const definitions = encodeASTSchema(
parse(`
scalar CountedScalar

type Query {
echo(value: CountedScalar!): String!
}
`),
)[0];

const result = await executeWithoutSchema({
document: parse(`
query UsesVariableTwice($value: CountedScalar!) {
first: echo(value: $value)
second: echo(value: $value)
}
`),
variableValues: {
value: "raw",
},
schemaFragment: {
schemaId: "test",
definitions,
resolvers: {
CountedScalar,
Query: {
echo(_source: unknown, args: { value: string }) {
argsAtResolver.push(args);
return args.value;
},
},
},
},
});

expect(await drainExecution(result)).toEqual({
data: {
first: "coerced:raw",
second: "coerced:raw",
},
});
expect(argsAtResolver).toEqual([
{ value: "coerced:raw" },
{ value: "coerced:raw" },
]);
expect(parseValueCalls).toBe(1);
});
});
28 changes: 15 additions & 13 deletions packages/supermassive/src/executeWithoutSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
FragmentDefinitionNode,
OperationDefinitionNode,
OperationTypeDefinitionNode,
VariableDefinitionNode,
} from "graphql";
import {
collectFields,
Expand Down Expand Up @@ -45,8 +46,8 @@ import type {
} from "./types";
import {
getArgumentValues,
getVariableValues,
getDirectiveValues,
getVariableDefinitionMap,
} from "./values";
import type { ExecutionHooks } from "./hooks/types";
import { arraysAreEqual } from "./utilities/array";
Expand Down Expand Up @@ -115,6 +116,9 @@ export interface ExecutionContext {
buildContextValue?: (contextValue?: unknown) => unknown;
operation: OperationDefinitionNode;
variableValues: { [variable: string]: unknown };
rawVariableValues: { [variable: string]: unknown };
variableDefinitions: { [variable: string]: VariableDefinitionNode };
variableCoercionResults: Map<string, VariableCoercionResult>;
fieldResolver: FunctionFieldResolver<unknown, unknown>;
typeResolver: TypeResolver<unknown, unknown>;
subscribeFieldResolver: FunctionFieldResolver<unknown, unknown>;
Expand All @@ -124,6 +128,11 @@ export interface ExecutionContext {
enablePerEventContext: boolean;
}

export type VariableCoercionResult =
| { status: "coerced"; value: unknown }
| { status: "missing" }
| { status: "error"; errors: ReadonlyArray<GraphQLError> };

/**
* Implements the "Executing requests" section of the GraphQL specification.
*
Expand Down Expand Up @@ -232,17 +241,7 @@ function buildExecutionContext(

// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
const variableDefinitions = operation.variableDefinitions ?? [];

const coercedVariableValues = getVariableValues(
schemaFragment,
variableDefinitions,
variableValues ?? {},
{ maxErrors: 50 },
);

if (coercedVariableValues.errors) {
return coercedVariableValues.errors;
}
const variableDefinitionMap = getVariableDefinitionMap(variableDefinitions);

return {
schemaFragment,
Expand All @@ -254,7 +253,10 @@ function buildExecutionContext(
: contextValue,
buildContextValue,
operation,
variableValues: coercedVariableValues.coerced,
variableValues: {},
rawVariableValues: variableValues ?? {},
variableDefinitions: variableDefinitionMap,
variableCoercionResults: new Map(),
fieldResolver: fieldResolver ?? defaultFieldResolver,
typeResolver: typeResolver ?? defaultTypeResolver,
subscribeFieldResolver: subscribeFieldResolver ?? defaultFieldResolver,
Expand Down
Loading
Loading