Skip to content

enhance: avoid instanceOf for type checkers #7191

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

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
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
5 changes: 5 additions & 0 deletions .changeset/tame-lizards-fly.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-tools/utils': minor
---

Introduce fast type checkers that avoid `instanceOf`
9 changes: 9 additions & 0 deletions .changeset/tidy-nails-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@graphql-tools/executor': patch
'@graphql-tools/schema': patch
'@graphql-tools/utils': patch
'@graphql-tools/load': patch
'@graphql-tools/mock': patch
---

Use faster type checkers, and avoid `instanceOf`
21 changes: 15 additions & 6 deletions packages/executor/src/execution/execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,13 @@ import {
GraphQLOutputType,
GraphQLSchema,
GraphQLTypeResolver,
isAbstractType,
isLeafType,
isListType,
isNonNullType,
isObjectType,
Kind,
locatedError,
OperationDefinitionNode,
SchemaMetaFieldDef,
TypeMetaFieldDef,
TypeNameMetaFieldDef,
validateSchema,
versionInfo,
} from 'graphql';
import {
Expand All @@ -39,9 +35,14 @@ import {
GraphQLResolveInfo,
GraphQLStreamDirective,
inspect,
isAbstractType,
isAsyncIterable,
isIterableObject,
isLeafType,
isListType,
isNonNullType,
isObjectLike,
isObjectType,
isPromise,
mapAsyncIterator,
Maybe,
Expand Down Expand Up @@ -396,6 +397,8 @@ export const getFragmentsFromDocument = memoize1(function getFragmentsFromDocume
return fragments;
});

const validSchemas = new WeakSet<GraphQLSchema>();

/**
* Constructs a ExecutionContext object from the arguments passed to
* execute, which we will pass throughout the other execution methods.
Expand Down Expand Up @@ -424,7 +427,13 @@ export function buildExecutionContext<TData = any, TVariables = any, TContext =
signal?.throwIfAborted();

// If the schema used for execution is invalid, throw an error.
assertValidSchema(schema);
if (!validSchemas.has(schema)) {
const validationErrors = validateSchema(schema);
if (validationErrors?.length) {
return validationErrors;
}
validSchemas.add(schema);
}

const fragments: Record<string, FragmentDefinitionNode> = getFragmentsFromDocument(document);

Expand Down
11 changes: 8 additions & 3 deletions packages/executor/src/execution/values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,20 @@ import {
coerceInputValue,
GraphQLError,
GraphQLSchema,
isInputType,
isNonNullType,
NamedTypeNode,
print,
typeFromAST,
valueFromAST,
VariableDefinitionNode,
} from 'graphql';
import { createGraphQLError, hasOwnProperty, inspect, printPathArray } from '@graphql-tools/utils';
import {
createGraphQLError,
hasOwnProperty,
inspect,
isInputType,
isNonNullType,
printPathArray,
} from '@graphql-tools/utils';

type CoercedVariableValues =
| { errors: ReadonlyArray<GraphQLError>; coerced?: never }
Expand Down
3 changes: 2 additions & 1 deletion packages/load/src/load-typedefs/collect-sources.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { createRequire } from 'module';
import { cwd } from 'process';
import { isSchema, Kind } from 'graphql';
import { Kind } from 'graphql';
import {
asArray,
debugTimerEnd,
debugTimerStart,
getDocumentNodeFromSchema,
isDocumentString,
isSchema,
parseGraphQLSDL,
Source,
} from '@graphql-tools/utils';
Expand Down
14 changes: 7 additions & 7 deletions packages/load/tests/loaders/schema/schema-from-export.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isSchema } from 'graphql';
import { GraphQLSchema } from 'graphql';
import { CodeFileLoader } from '@graphql-tools/code-file-loader';
import { loadSchema, loadSchemaSync } from '@graphql-tools/load';
import { runTests, useMonorepo } from '../../../../testing/utils.js';
Expand Down Expand Up @@ -28,7 +28,7 @@ describe('Schema From Export', () => {
cwd: __dirname,
},
);
expect(isSchema(result)).toBeTruthy();
expect(result).toBeInstanceOf(GraphQLSchema);
});

it('should load the schema (with extend) correctly from module.exports', async () => {
Expand All @@ -39,7 +39,7 @@ describe('Schema From Export', () => {
cwd: __dirname,
},
);
expect(isSchema(result)).toBeTruthy();
expect(result).toBeInstanceOf(GraphQLSchema);
const QueryType = result.getQueryType();
assertNonMaybe(QueryType);
expect(QueryType.getFields()['hello']).toBeDefined();
Expand All @@ -53,7 +53,7 @@ describe('Schema From Export', () => {
cwd: __dirname,
},
);
expect(isSchema(result)).toBeTruthy();
expect(result).toBeInstanceOf(GraphQLSchema);
});

it('should load the schema correctly from default export', async () => {
Expand All @@ -64,7 +64,7 @@ describe('Schema From Export', () => {
cwd: __dirname,
},
);
expect(isSchema(result)).toBeTruthy();
expect(result).toBeInstanceOf(GraphQLSchema);
});

if (mode === 'async') {
Expand All @@ -76,7 +76,7 @@ describe('Schema From Export', () => {
cwd: __dirname,
},
);
expect(isSchema(result)).toBeTruthy();
expect(result).toBeInstanceOf(GraphQLSchema);
});

it('should load the schema correctly from promise export', async () => {
Expand All @@ -87,7 +87,7 @@ describe('Schema From Export', () => {
cwd: __dirname,
},
);
expect(isSchema(result)).toBeTruthy();
expect(result).toBeInstanceOf(GraphQLSchema);
});
}

Expand Down
7 changes: 4 additions & 3 deletions packages/load/tests/loaders/schema/schema-from-json.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { readFileSync } from 'fs';
import { join } from 'path';
import { isSchema, isSpecifiedScalarType } from 'graphql';
import { GraphQLSchema } from 'graphql';
import { JsonFileLoader } from '@graphql-tools/json-file-loader';
import { loadSchema, loadSchemaSync } from '@graphql-tools/load';
import { isSpecifiedScalarType } from '@graphql-tools/utils';
import { runTests, useMonorepo } from '../../../../testing/utils.js';

const monorepo = useMonorepo({
Expand All @@ -27,14 +28,14 @@ describe('Schema From Export', () => {
loaders: [new JsonFileLoader()],
cwd: __dirname,
});
expect(isSchema(schema)).toBeTruthy();
expect(schema).toBeInstanceOf(GraphQLSchema);
});
it('should load the schema with correct descriptions', async () => {
const schema = await load('./test-files/githunt.json', {
loaders: [new JsonFileLoader()],
cwd: __dirname,
});
expect(isSchema(schema)).toBeTruthy();
expect(schema).toBeInstanceOf(GraphQLSchema);
for (const typeName in schema.getTypeMap()) {
const githuntJsonFile = readFileSync(join(__dirname, './test-files/githunt.json'), 'utf-8');
const introspectionSchema = JSON.parse(githuntJsonFile).__schema;
Expand Down
2 changes: 1 addition & 1 deletion packages/merge/src/typedefs-mergers/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export function isStringTypes(types: any): types is string {
}

export function isSourceTypes(types: any): types is Source {
return types instanceof Source;
return types?.[Symbol.toStringTag] === 'Source';
}

export function extractType(type: TypeNode): NamedTypeNode {
Expand Down
6 changes: 2 additions & 4 deletions packages/mock/src/MockStore.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import stringify from 'fast-json-stable-stringify';
import { GraphQLOutputType, GraphQLSchema, GraphQLString } from 'graphql';
import {
getNullableType,
GraphQLOutputType,
GraphQLSchema,
GraphQLString,
isAbstractType,
isCompositeType,
isEnumType,
Expand All @@ -12,7 +10,7 @@ import {
isNullableType,
isObjectType,
isScalarType,
} from 'graphql';
} from '@graphql-tools/utils';
import { deepResolveMockList, isMockList } from './MockList.js';
import {
assertIsRef,
Expand Down
3 changes: 1 addition & 2 deletions packages/mock/src/addMocksToSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import {
GraphQLTypeResolver,
GraphQLUnionType,
isSchema,
isUnionType,
} from 'graphql';
import { addResolversToSchema } from '@graphql-tools/schema';
import { IResolvers, MapperKind, mapSchema } from '@graphql-tools/utils';
import { IResolvers, isUnionType, MapperKind, mapSchema } from '@graphql-tools/utils';
import { createMockStore } from './MockStore.js';
import { IMocks, IMockStore, isRef, TypePolicy } from './types.js';
import { copyOwnProps, isObject, isRootType } from './utils.js';
Expand Down
12 changes: 6 additions & 6 deletions packages/schema/src/addResolversToSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ import {
GraphQLScalarType,
GraphQLSchema,
GraphQLUnionType,
isEnumType,
isInterfaceType,
isObjectType,
isScalarType,
isSpecifiedScalarType,
isUnionType,
} from 'graphql';
import {
forEachDefaultValue,
forEachField,
healSchema,
IAddResolversToSchemaOptions,
IResolvers,
isEnumType,
isInterfaceType,
isObjectType,
isScalarType,
isSpecifiedScalarType,
isUnionType,
MapperKind,
mapSchema,
parseInputValue,
Expand Down
10 changes: 8 additions & 2 deletions packages/schema/src/assertResolversPresent.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { getNamedType, GraphQLField, GraphQLSchema, isScalarType } from 'graphql';
import { forEachField, IResolverValidationOptions, ValidatorBehavior } from '@graphql-tools/utils';
import { GraphQLField, GraphQLSchema } from 'graphql';
import {
forEachField,
getNamedType,
IResolverValidationOptions,
isScalarType,
ValidatorBehavior,
} from '@graphql-tools/utils';

export function assertResolversPresent(
schema: GraphQLSchema,
Expand Down
9 changes: 2 additions & 7 deletions packages/utils/src/addTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,10 @@
// enhanceSchema can fill this gap by adding an additional round of rewiring.
//

import {
GraphQLDirective,
GraphQLNamedType,
GraphQLSchema,
isDirective,
isNamedType,
} from 'graphql';
import { GraphQLDirective, GraphQLNamedType, GraphQLSchema, isDirective } from 'graphql';
import { getObjectTypeFromTypeMap } from './getObjectTypeFromTypeMap.js';
import { rewireTypes } from './rewire.js';
import { isNamedType } from './typeCheckers.js';

export function addTypes(
schema: GraphQLSchema,
Expand Down
3 changes: 2 additions & 1 deletion packages/utils/src/astFromType.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { inspect } from 'cross-inspect';
import { GraphQLType, isListType, isNonNullType, Kind, TypeNode } from 'graphql';
import { GraphQLType, Kind, TypeNode } from 'graphql';
import { isListType, isNonNullType } from './typeCheckers.js';

export function astFromType(type: GraphQLType): TypeNode {
if (isNonNullType(type)) {
Expand Down
11 changes: 4 additions & 7 deletions packages/utils/src/astFromValue.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import { inspect } from 'cross-inspect';
import { Kind, ObjectFieldNode, ValueNode, type GraphQLInputType } from 'graphql';
import { astFromValueUntyped } from './astFromValueUntyped.js';
import { isIterableObject, isObjectLike } from './jsutils.js';
import {
GraphQLInputType,
isEnumType,
isInputObjectType,
isLeafType,
isListType,
isNonNullType,
Kind,
ObjectFieldNode,
ValueNode,
} from 'graphql';
import { astFromValueUntyped } from './astFromValueUntyped.js';
import { isIterableObject, isObjectLike } from './jsutils.js';
} from './typeCheckers.js';
import { Maybe } from './types.js';

/**
Expand Down
18 changes: 10 additions & 8 deletions packages/utils/src/build-operation-for-field.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
ArgumentNode,
getNamedType,
GraphQLArgument,
GraphQLField,
GraphQLInputType,
Expand All @@ -10,13 +9,6 @@ import {
GraphQLObjectType,
GraphQLSchema,
InlineFragmentNode,
isEnumType,
isInterfaceType,
isListType,
isNonNullType,
isObjectType,
isScalarType,
isUnionType,
Kind,
ListTypeNode,
NonNullTypeNode,
Expand All @@ -28,6 +20,16 @@ import {
VariableDefinitionNode,
} from 'graphql';
import { getDefinedRootType, getRootTypeNames } from './rootTypes.js';
import {
getNamedType,
isEnumType,
isInterfaceType,
isListType,
isNonNullType,
isObjectType,
isScalarType,
isUnionType,
} from './typeCheckers.js';

let operationVariables: VariableDefinitionNode[] = [];
let fieldTypeMap = new Map();
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/src/collectFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ import {
GraphQLSchema,
GraphQLSkipDirective,
InlineFragmentNode,
isAbstractType,
Kind,
SelectionSetNode,
typeFromAST,
} from 'graphql';
import { AccumulatorMap } from './AccumulatorMap.js';
import { GraphQLDeferDirective } from './directives.js';
import { memoize5 } from './memoize.js';
import { isAbstractType } from './typeCheckers.js';

export interface PatchFields {
label: string | undefined;
Expand Down
5 changes: 3 additions & 2 deletions packages/utils/src/forEachDefaultValue.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { getNamedType, GraphQLSchema, isInputObjectType, isObjectType } from 'graphql';
import { GraphQLSchema } from 'graphql';
import { IDefaultValueIteratorFn } from './Interfaces.js';
import { isInputObjectType, isIntrospectionType, isObjectType } from './typeCheckers.js';

export function forEachDefaultValue(schema: GraphQLSchema, fn: IDefaultValueIteratorFn): void {
const typeMap = schema.getTypeMap();
for (const typeName in typeMap) {
const type = typeMap[typeName];

if (!getNamedType(type).name.startsWith('__')) {
if (!isIntrospectionType(type)) {
if (isObjectType(type)) {
const fields = type.getFields();
for (const fieldName in fields) {
Expand Down
Loading
Loading