Skip to content

alternative refactor #3660

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

Closed
wants to merge 10 commits into from
11 changes: 6 additions & 5 deletions integrationTests/ts/basic-test.ts
Original file line number Diff line number Diff line change
@@ -23,12 +23,13 @@ const queryType: GraphQLObjectType = new GraphQLObjectType({

const schema: GraphQLSchema = new GraphQLSchema({ query: queryType });

const result: ExecutionResult = graphqlSync({
schema,
source: `
const result: ExecutionResult | AsyncGenerator<ExecutionResult, void, void> =
graphqlSync({
schema,
source: `
query helloWho($who: String){
test(who: $who)
}
`,
variableValues: { who: 'Dolly' },
});
variableValues: { who: 'Dolly' },
});
5 changes: 4 additions & 1 deletion src/__tests__/starWarsIntrospection-test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { expect } from 'chai';
import { assert, expect } from 'chai';
import { describe, it } from 'mocha';

import { isAsyncIterable } from '../jsutils/isAsyncIterable';

import { graphqlSync } from '../graphql';

import { StarWarsSchema } from './starWarsSchema';

function queryStarWars(source: string) {
const result = graphqlSync({ schema: StarWarsSchema, source });
expect(Object.keys(result)).to.deep.equal(['data']);
assert(!isAsyncIterable(result));
return result.data;
}

32 changes: 28 additions & 4 deletions src/execution/__tests__/executor-test.ts
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ import { describe, it } from 'mocha';
import { expectJSON } from '../../__testUtils__/expectJSON';

import { inspect } from '../../jsutils/inspect';
import { isAsyncIterable } from '../../jsutils/isAsyncIterable';

import { Kind } from '../../language/kinds';
import { parse } from '../../language/parser';
@@ -19,7 +20,7 @@ import {
import { GraphQLBoolean, GraphQLInt, GraphQLString } from '../../type/scalars';
import { GraphQLSchema } from '../../type/schema';

import { execute, executeSync } from '../execute';
import { execute, executeSubscriptionEvent, executeSync } from '../execute';

describe('Execute: Handles basic execution tasks', () => {
it('executes arbitrary code', async () => {
@@ -833,7 +834,7 @@ describe('Execute: Handles basic execution tasks', () => {
expect(result).to.deep.equal({ data: { c: 'd' } });
});

it('uses the subscription schema for subscriptions', () => {
it('uses the subscription schema for subscriptions', async () => {
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Q',
@@ -852,11 +853,22 @@ describe('Execute: Handles basic execution tasks', () => {
query Q { a }
subscription S { a }
`);
const rootValue = { a: 'b', c: 'd' };
const rootValue = {
// eslint-disable-next-line @typescript-eslint/require-await
async *a() {
yield { a: 'b' }; /* c8 ignore start */
} /* c8 ignore stop */,
c: 'd',
};
const operationName = 'S';

const result = executeSync({ schema, document, rootValue, operationName });
expect(result).to.deep.equal({ data: { a: 'b' } });

assert(isAsyncIterable(result));
expect(await result.next()).to.deep.equal({
value: { data: { a: 'b' } },
done: false,
});
});

it('resolves to an error if schema does not support operation', () => {
@@ -894,6 +906,18 @@ describe('Execute: Handles basic execution tasks', () => {

expectJSON(
executeSync({ schema, document, operationName: 'S' }),
).toDeepEqual({
errors: [
{
message:
'Schema is not configured to execute subscription operation.',
locations: [{ line: 4, column: 7 }],
},
],
});

expectJSON(
executeSubscriptionEvent({ schema, document, operationName: 'S' }),
).toDeepEqual({
data: null,
errors: [
4 changes: 3 additions & 1 deletion src/execution/__tests__/lists-test.ts
Original file line number Diff line number Diff line change
@@ -85,7 +85,9 @@ describe('Execute: Accepts async iterables as list value', () => {

function completeObjectList(
resolve: GraphQLFieldResolver<{ index: number }, unknown>,
): PromiseOrValue<ExecutionResult> {
): PromiseOrValue<
ExecutionResult | AsyncGenerator<ExecutionResult, void, void>
> {
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
10 changes: 8 additions & 2 deletions src/execution/__tests__/nonnull-test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { expect } from 'chai';
import { assert, expect } from 'chai';
import { describe, it } from 'mocha';

import { expectJSON } from '../../__testUtils__/expectJSON';

import { isAsyncIterable } from '../../jsutils/isAsyncIterable';
import type { PromiseOrValue } from '../../jsutils/PromiseOrValue';

import { parse } from '../../language/parser';

import { GraphQLNonNull, GraphQLObjectType } from '../../type/definition';
@@ -109,7 +112,9 @@ const schema = buildSchema(`
function executeQuery(
query: string,
rootValue: unknown,
): ExecutionResult | Promise<ExecutionResult> {
): PromiseOrValue<
ExecutionResult | AsyncGenerator<ExecutionResult, void, void>
> {
return execute({ schema, document: parse(query), rootValue });
}

@@ -132,6 +137,7 @@ async function executeSyncAndAsync(query: string, rootValue: unknown) {
rootValue,
});

assert(!isAsyncIterable(syncResult));
expectJSON(asyncResult).toDeepEqual(patchData(syncResult));
return syncResult;
}
75 changes: 50 additions & 25 deletions src/execution/__tests__/subscribe-test.ts
Original file line number Diff line number Diff line change
@@ -15,7 +15,7 @@ import { GraphQLBoolean, GraphQLInt, GraphQLString } from '../../type/scalars';
import { GraphQLSchema } from '../../type/schema';

import type { ExecutionArgs, ExecutionResult } from '../execute';
import { createSourceEventStream, subscribe } from '../execute';
import { createSourceEventStream, execute, subscribe } from '../execute';

import { SimplePubSub } from './simplePubSub';

@@ -122,7 +122,7 @@ function createSubscription(pubsub: SimplePubSub<Email>) {
}),
};

return subscribe({ schema: emailSchema, document, rootValue: data });
return execute({ schema: emailSchema, document, rootValue: data });
}

// TODO: consider adding this method to testUtils (with tests)
@@ -150,22 +150,46 @@ function expectPromise(maybePromise: unknown) {
};
}

// TODO: consider adding this method to testUtils (with tests)
// TODO: consider adding these method to testUtils (with tests)
function expectEqualPromisesOrValues<T>(
value1: PromiseOrValue<T>,
value2: PromiseOrValue<T>,
items: ReadonlyArray<PromiseOrValue<T>>,
): PromiseOrValue<T> {
if (isPromise(value1)) {
assert(isPromise(value2));
return Promise.all([value1, value2]).then((resolved) => {
expectJSON(resolved[1]).toDeepEqual(resolved[0]);
return resolved[0];
});
if (isPromise(items[0])) {
if (assertAllPromises(items)) {
return Promise.all(items).then(expectMatchingValues);
}
} else if (assertNoPromises(items)) {
return expectMatchingValues(items);
}
/* c8 ignore next 3 */
// Not reachable, all possible output types have been considered.
assert(false, 'Receives mixture of promises and values.');
}

assert(!isPromise(value2));
expectJSON(value2).toDeepEqual(value1);
return value1;
function expectMatchingValues<T>(values: ReadonlyArray<T>): T {
const remainingValues = values.slice(1);
for (const value of remainingValues) {
expectJSON(value).toDeepEqual(values[0]);
}
return values[0];
}

function assertAllPromises<T>(
items: ReadonlyArray<PromiseOrValue<T>>,
): items is ReadonlyArray<Promise<T>> {
for (const item of items) {
assert(isPromise(item));
}
return true;
}

function assertNoPromises<T>(
items: ReadonlyArray<PromiseOrValue<T>>,
): items is ReadonlyArray<T> {
for (const item of items) {
assert(!isPromise(item));
}
return true;
}

const DummyQueryType = new GraphQLObjectType({
@@ -195,10 +219,11 @@ function subscribeWithBadFn(
function subscribeWithBadArgs(
args: ExecutionArgs,
): PromiseOrValue<ExecutionResult | AsyncIterable<unknown>> {
return expectEqualPromisesOrValues(
subscribe(args),
return expectEqualPromisesOrValues([
execute(args),
createSourceEventStream(args),
);
subscribe(args),
]);
}

/* eslint-disable @typescript-eslint/require-await */
@@ -220,7 +245,7 @@ describe('Subscription Initialization Phase', () => {
yield { foo: 'FooValue' };
}

const subscription = subscribe({
const subscription = execute({
schema,
document: parse('subscription { foo }'),
rootValue: { foo: fooGenerator },
@@ -256,7 +281,7 @@ describe('Subscription Initialization Phase', () => {
}),
});

const subscription = subscribe({
const subscription = execute({
schema,
document: parse('subscription { foo }'),
});
@@ -294,7 +319,7 @@ describe('Subscription Initialization Phase', () => {
}),
});

const promise = subscribe({
const promise = execute({
schema,
document: parse('subscription { foo }'),
});
@@ -329,7 +354,7 @@ describe('Subscription Initialization Phase', () => {
yield { foo: 'FooValue' };
}

const subscription = subscribe({
const subscription = execute({
schema,
document: parse('subscription { foo }'),
rootValue: { customFoo: fooGenerator },
@@ -379,7 +404,7 @@ describe('Subscription Initialization Phase', () => {
}),
});

const subscription = subscribe({
const subscription = execute({
schema,
document: parse('subscription { foo bar }'),
});
@@ -530,7 +555,7 @@ describe('Subscription Initialization Phase', () => {
}
`);

// If we receive variables that cannot be coerced correctly, subscribe() will
// If we receive variables that cannot be coerced correctly, execute() will
// resolve to an ExecutionResult that contains an informative error description.
const result = subscribeWithBadArgs({ schema, document, variableValues });
expectJSON(result).toDeepEqual({
@@ -945,7 +970,7 @@ describe('Subscription Publish Phase', () => {
});

const document = parse('subscription { newMessage }');
const subscription = subscribe({ schema, document });
const subscription = execute({ schema, document });
assert(isAsyncIterable(subscription));

expect(await subscription.next()).to.deep.equal({
@@ -1006,7 +1031,7 @@ describe('Subscription Publish Phase', () => {
});

const document = parse('subscription { newMessage }');
const subscription = subscribe({ schema, document });
const subscription = execute({ schema, document });
assert(isAsyncIterable(subscription));

expect(await subscription.next()).to.deep.equal({
80 changes: 80 additions & 0 deletions src/execution/compiledDocument.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { ObjMap } from '../jsutils/ObjMap';

import { GraphQLError } from '../error/GraphQLError';

import type {
FragmentDefinitionNode,
OperationDefinitionNode,
} from '../language/ast';
import { Kind } from '../language/kinds';

import { assertValidSchema } from '../type/validate';

import type { ExecutionArgs } from './execute';

/**
* Data that must be available at all points during query execution.
*
* Namely, schema of the type system that is currently executing,
* and the fragments defined in the query document
*/
export interface ExecutionContext {
fragments: ObjMap<FragmentDefinitionNode>;
operation: OperationDefinitionNode;
}

/**
* Constructs a ExecutionContext object from the arguments passed to
* execute, which we will pass throughout the other execution methods.
*
* Throws a GraphQLError if a valid execution context cannot be created.
*
* TODO: consider no longer exporting this function
* @internal
*/
export function buildExecutionContext(
args: ExecutionArgs,
): ReadonlyArray<GraphQLError> | ExecutionContext {
const { schema, document, operationName } = args;

// If the schema used for execution is invalid, throw an error.
assertValidSchema(schema);

let operation: OperationDefinitionNode | undefined;
const fragments: ObjMap<FragmentDefinitionNode> = Object.create(null);
for (const definition of document.definitions) {
switch (definition.kind) {
case Kind.OPERATION_DEFINITION:
if (operationName == null) {
if (operation !== undefined) {
return [
new GraphQLError(
'Must provide operation name if query contains multiple operations.',
),
];
}
operation = definition;
} else if (definition.name?.value === operationName) {
operation = definition;
}
break;
case Kind.FRAGMENT_DEFINITION:
fragments[definition.name.value] = definition;
break;
default:
// ignore non-executable definitions
}
}

if (!operation) {
if (operationName != null) {
return [new GraphQLError(`Unknown operation named "${operationName}".`)];
}
return [new GraphQLError('Must provide an operation.')];
}

return {
fragments,
operation,
};
}
Loading