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

WIP: Some other refactor #3096

Merged
merged 13 commits into from
Jun 23, 2021
Merged
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/brave-rats-march.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-tools/wrap': major
---

BREAKING - remove makeRemoteExecutableSchema
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@
"packages/load/tests/loaders/schema",
"website",
"scripts",
"packages/loaders/code-file/tests/test-files"
"packages/loaders/code-file/tests/test-files",
"packages/loaders/git/tests/test-files"
],
"globals":{
"BigInt": true
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
- name: Lint
run: yarn lint
build:
name: Build on ${{matrix.os}} GraphQL v${{matrix.graphql_version}}
name: Type Check on GraphQL v${{matrix.graphql_version}}
runs-on: ubuntu-latest
strategy:
matrix:
Expand All @@ -55,9 +55,9 @@ jobs:
- name: Install Dependencies using Yarn
run: yarn install --ignore-engines && git checkout yarn.lock
- name: Build
run: yarn ts:transpile
run: yarn ts:check
test:
name: Test, Node ${{matrix.node_version}} and GraphQL v${{matrix.graphql_version}}
name: Unit Test on Node ${{matrix.node_version}} and GraphQL v${{matrix.graphql_version}}
runs-on: ubuntu-latest
strategy:
matrix:
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"postinstall": "patch-package && husky install",
"predeploy:website": "yarn build:api-docs",
"deploy:website": "cd website && yarn deploy",
"ts:transpile": "concurrently \"tsc --project tsconfig.build.json\" \"tsc --project tsconfig.build.es5.json\"",
"ts:check": "tsc --noEmit --incremental",
"ts:transpile": "concurrently \"tsc --project tsconfig.build.json --incremental\" \"tsc --project tsconfig.build.es5.json --incremental\"",
"clean-dist": "rimraf \"packages/**/dist\" && rimraf \"packages/**/dist-es5\" && rimraf \".bob\"",
"build": "yarn ts:transpile && bob build",
"build:api-docs": "node scripts/build-api-docs.js",
Expand Down
2 changes: 1 addition & 1 deletion packages/batch-delegate/src/batchDelegateToSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BatchDelegateOptions } from './types';

import { getLoader } from './getLoader';

export function batchDelegateToSchema(options: BatchDelegateOptions): any {
export function batchDelegateToSchema<TContext = any>(options: BatchDelegateOptions<TContext>): any {
const key = options.key;
if (key == null) {
return null;
Expand Down
2 changes: 1 addition & 1 deletion packages/batch-delegate/tests/basic.example.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ describe('batch delegation within basic stitching example', () => {

expect(numCalls).toEqual(1);
expect(result.errors).toBeUndefined();
expect(result.data!.trendingChirps[0].chirpedAtUser.email).not.toBe(null);
expect(result.data!['trendingChirps'][0].chirpedAtUser.email).not.toBe(null);
});

test('works with key arrays', async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/batch-delegate/tests/typeMerging.example.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ describe('merging using type merging', () => {
Query: {
mostStockedProduct: () => inventory.find(i => i.upc === '3'),
_products: (_root, { representations }) => {
return representations.map((rep: Record<string, any>) => ({ ...rep, ...inventory.find(i => i.upc === rep.upc) }));
return representations.map((rep: Record<string, any>) => ({ ...rep, ...inventory.find(i => i.upc === rep['upc']) }));
},
},
},
Expand Down
2 changes: 1 addition & 1 deletion packages/batch-delegate/tests/withTransforms.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ describe('works with complex transforms', () => {
]
}),
resultTransformer: (results, delegationContext) => {
const userIds = delegationContext.args.userIds;
const userIds = delegationContext.args['userIds'];
const booksByUserIds = results.reduce(
(acc: any, { userId, books }: { userId: string, books: any[] }) => {
acc[userId] = books
Expand Down
18 changes: 8 additions & 10 deletions packages/batch-execute/src/createBatchingExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,18 @@ function createLoadFn(
}
}

const executionResults: Array<ValueOrPromise<ExecutionResult>> = [];
execBatches.forEach(execBatch => {
const executionResults: Array<ValueOrPromise<ExecutionResult>> = execBatches.map(execBatch => {
const mergedExecutionParams = mergeExecutionParams(execBatch, extensionsReducer);
executionResults.push(new ValueOrPromise(() => executor(mergedExecutionParams)));
return new ValueOrPromise(() => executor(mergedExecutionParams));
});

return ValueOrPromise.all(executionResults)
.then(resultBatches => {
let results: Array<ExecutionResult> = [];
resultBatches.forEach((resultBatch, index) => {
results = [...results, ...splitResult(resultBatch!, execBatches[index].length)];
});
return results;
})
.then(resultBatches =>
resultBatches.reduce(
(results, resultBatch, index) => results.concat(splitResult(resultBatch, execBatches[index].length)),
new Array<ExecutionResult<Record<string, any>>>()
)
)
.resolve();
};
}
Expand Down
13 changes: 8 additions & 5 deletions packages/batch-execute/src/mergeExecutionParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,22 +68,25 @@ export function mergeExecutionParams(

let operation: Maybe<OperationTypeNode>;

execs.forEach((executionParams, index) => {
for (const index in execs) {
const executionParams = execs[index];
const prefixedExecutionParams = prefixExecutionParams(createPrefix(index), executionParams);

prefixedExecutionParams.document.definitions.forEach(def => {
for (const def of prefixedExecutionParams.document.definitions) {
if (isOperationDefinition(def)) {
operation = def.operation;
mergedSelections.push(...def.selectionSet.selections);
mergedVariableDefinitions.push(...(def.variableDefinitions ?? []));
if (def.variableDefinitions) {
mergedVariableDefinitions.push(...def.variableDefinitions);
}
}
if (isFragmentDefinition(def)) {
mergedFragmentDefinitions.push(def);
}
});
}
Object.assign(mergedVariables, prefixedExecutionParams.variables);
mergedExtensions = extensionsReducer(mergedExtensions, executionParams);
});
}

if (operation == null) {
throw new Error('Could not identify operation type. Did the document only include fragment definitions?');
Expand Down
2 changes: 1 addition & 1 deletion packages/batch-execute/src/prefix.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// adapted from https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js

export function createPrefix(index: number): string {
export function createPrefix(index: string): string {
return `graphqlTools${index}_`;
}

Expand Down
35 changes: 8 additions & 27 deletions packages/batch-execute/src/splitResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,60 +9,41 @@ import { parseKey } from './prefix';
/**
* Split and transform result of the query produced by the `merge` function
*/
export function splitResult(mergedResult: ExecutionResult, numResults: number): Array<ExecutionResult> {
export function splitResult({ data, errors }: ExecutionResult, numResults: number): Array<ExecutionResult> {
const splitResults: Array<ExecutionResult> = [];
for (let i = 0; i < numResults; i++) {
splitResults.push({});
}

const data = mergedResult.data;
if (data) {
Object.keys(data).forEach(prefixedKey => {
for (const prefixedKey in data) {
const parsedKey = parseKey(prefixedKey);
assertSome(parsedKey, "'parsedKey' should not be null.");
const { index, originalKey } = parsedKey;
const result = splitResults[index];
if (result == null) {
return;
continue;
}
if (result.data == null) {
result.data = { [originalKey]: data[prefixedKey] };
} else {
result.data[originalKey] = data[prefixedKey];
}
});
}
}

const errors = mergedResult.errors;
if (errors) {
const newErrors: Record<string, Array<GraphQLError>> = Object.create(null);
errors.forEach(error => {
for (const error of errors) {
if (error.path) {
const parsedKey = parseKey(error.path[0] as string);
if (parsedKey) {
const { index, originalKey } = parsedKey;
const newError = relocatedError(error, [originalKey, ...error.path.slice(1)]);
if (!newErrors[index]) {
newErrors[index] = [newError];
} else {
newErrors[index].push(newError);
}
return;
const errors = (splitResults[index].errors = (splitResults[index].errors || []) as GraphQLError[]);
errors.push(newError);
}
}

splitResults.forEach((_splitResult, index) => {
if (!newErrors[index]) {
newErrors[index] = [error];
} else {
newErrors[index].push(error);
}
});
});

Object.keys(newErrors).forEach(index => {
splitResults[index].errors = newErrors[index];
});
}
}

return splitResults;
Expand Down
4 changes: 3 additions & 1 deletion packages/delegate/src/Transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ export class Transformer<TContext = Record<string, any>> {
constructor(context: DelegationContext<TContext>, binding: DelegationBinding<TContext> = defaultDelegationBinding) {
this.delegationContext = context;
const delegationTransforms: Array<Transform> = binding(this.delegationContext);
delegationTransforms.forEach(transform => this.addTransform(transform, {}));
for (const transform of delegationTransforms) {
this.addTransform(transform, {});
}
}

private addTransform(transform: Transform, context = {}) {
Expand Down
17 changes: 8 additions & 9 deletions packages/delegate/src/createRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
typeFromAST,
NamedTypeNode,
GraphQLInputType,
GraphQLArgument,
VariableDefinitionNode,
SelectionSetNode,
DefinitionNode,
Expand Down Expand Up @@ -107,15 +106,15 @@ export function createRequest({
const variableDefinitionMap = Object.create(null);

if (sourceSchema != null && variableDefinitions != null) {
variableDefinitions.forEach(def => {
for (const def of variableDefinitions) {
const varName = def.variable.name.value;
variableDefinitionMap[varName] = def;
const varType = typeFromAST(sourceSchema, def.type as NamedTypeNode) as GraphQLInputType;
const serializedValue = serializeInputValue(varType, variableValues?.[varName]);
if (serializedValue !== undefined) {
newVariables[varName] = serializedValue;
}
});
}
}

if (sourceParentType != null && sourceFieldName != null) {
Expand All @@ -130,7 +129,7 @@ export function createRequest({

const rootfieldNode: FieldNode = {
kind: Kind.FIELD,
arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),
arguments: Object.values(argumentNodeMap),
name: {
kind: Kind.NAME,
value:
Expand All @@ -152,17 +151,17 @@ export function createRequest({
kind: Kind.OPERATION_DEFINITION,
name: operationName,
operation: targetOperation,
variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),
variableDefinitions: Object.values(variableDefinitionMap),
selectionSet: {
kind: Kind.SELECTION_SET,
selections: [rootfieldNode],
},
};

let definitions: Array<DefinitionNode> = [operationDefinition];
const definitions: Array<DefinitionNode> = [operationDefinition];

if (fragments != null) {
definitions = definitions.concat(Object.keys(fragments).map(fragmentName => fragments[fragmentName]));
definitions.push(...Object.values(fragments));
}

const document: DocumentNode = {
Expand All @@ -184,7 +183,7 @@ function updateArgumentsWithDefaults(
variableValues: Record<string, any>
): void {
const sourceField = sourceParentType.getFields()[sourceFieldName];
sourceField.args.forEach((argument: GraphQLArgument) => {
for (const argument of sourceField.args) {
const argName = argument.name;
const sourceArgType = argument.type;

Expand All @@ -202,5 +201,5 @@ function updateArgumentsWithDefaults(
);
}
}
});
}
}
26 changes: 10 additions & 16 deletions packages/delegate/src/externalObjects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export function mergeExternalObjects(
const results: Array<any> = [];
let errors: Array<GraphQLError> = [];

sources.forEach((source, index) => {
for (const index in sources) {
const source = sources[index];
if (source instanceof Error || source === null) {
const selectionSet = selectionSets[index];
const fieldNodes = collectFields(
Expand All @@ -56,39 +57,32 @@ export function mergeExternalObjects(
Object.create(null)
);
const nullResult = {};
Object.keys(fieldNodes).forEach(responseKey => {
for (const responseKey in fieldNodes) {
if (source instanceof GraphQLError) {
nullResult[responseKey] = relocatedError(source, path.concat([responseKey]));
} else if (source instanceof Error) {
nullResult[responseKey] = locatedError(source, fieldNodes[responseKey], path.concat([responseKey]));
} else {
nullResult[responseKey] = null;
}
});
}
results.push(nullResult);
} else {
errors = errors.concat(source[UNPATHED_ERRORS_SYMBOL]);
results.push(source);
}
});
}

const combinedResult: ExternalObject = results.reduce(mergeDeep, target);

const newFieldSubschemaMap = target[FIELD_SUBSCHEMA_MAP_SYMBOL] ?? Object.create(null);

results.forEach((source: ExternalObject) => {
const newFieldSubschemaMap = results.reduce((newFieldSubschemaMap, source) => {
const objectSubschema = source[OBJECT_SUBSCHEMA_SYMBOL];
const fieldSubschemaMap = source[FIELD_SUBSCHEMA_MAP_SYMBOL];
if (fieldSubschemaMap === undefined) {
Object.keys(source).forEach(responseKey => {
newFieldSubschemaMap[responseKey] = objectSubschema;
});
} else {
Object.keys(source).forEach(responseKey => {
newFieldSubschemaMap[responseKey] = fieldSubschemaMap[responseKey] ?? objectSubschema;
});
for (const responseKey in source) {
newFieldSubschemaMap[responseKey] = fieldSubschemaMap?.[responseKey] ?? objectSubschema;
}
});
return newFieldSubschemaMap;
}, target[FIELD_SUBSCHEMA_MAP_SYMBOL] ?? Object.create(null));

combinedResult[FIELD_SUBSCHEMA_MAP_SYMBOL] = newFieldSubschemaMap;
combinedResult[OBJECT_SUBSCHEMA_SYMBOL] = target[OBJECT_SUBSCHEMA_SYMBOL];
Expand Down
Loading