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

Enabling graphql-validate-fixtures compatibility with varying file types #2658

Open
wants to merge 4 commits into
base: main
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/graphql-validate-fixtures/package.json
Expand Up @@ -25,12 +25,15 @@
"node": "^14.17.0 || >=16.0.0"
},
"dependencies": {
"@graphql-tools/load-files": "^6.6.1",
"@graphql-tools/merge": "^8.4.1",
"chalk": "^4.0.0",
"fs-extra": "^9.1.0",
"glob": "^7.1.2",
"graphql": ">=14.5.0 <16.0.0",
"graphql-config": "^4.3.0",
"graphql-config-utilities": "^4.1.3",
"graphql-tag": "^2.12.6",
"graphql-tool-utilities": "^3.0.3",
"yargs": "^15.3.1"
},
Expand Down
45 changes: 31 additions & 14 deletions packages/graphql-validate-fixtures/src/index.ts
@@ -1,15 +1,16 @@
import {resolve} from 'path';

import {readFile, readJSON} from 'fs-extra';
import {readJSON} from 'fs-extra';
import type {GraphQLSchema} from 'graphql';
import {Source, parse, concatAST} from 'graphql';
import {concatAST, parse, Source} from 'graphql';
import type {GraphQLProjectConfig} from 'graphql-config';
import {loadConfig} from 'graphql-config';
import {
getGraphQLProjectIncludedFilePaths,
getGraphQLProjects,
} from 'graphql-config-utilities';
import {compile} from 'graphql-tool-utilities';
import {loadFilesSync} from '@graphql-tools/load-files';

import type {Fixture, Validation, GraphQLProjectAST} from './validate';
import {
Expand Down Expand Up @@ -55,12 +56,28 @@ async function getOperationsForProject(
projectConfig,
);

const operationSources = await Promise.all(
operationPaths.map(loadOperationSource),
);
const sanitizedSources = operationPaths.map((filePath: string) => {
const file = loadFilesSync(filePath);

if (!file || file.length === 0) {
throw new Error(`Error loading '${filePath}'}`);
}

if (file[0].__esModule) {
for (const key of Object.keys(file[0])) {
if (Object.keys(file[0][key]).includes('kind')) {
return new Source(file[0][key].loc.source.body, filePath);
}
}
} else if (Object.keys(file[0]).includes('kind')) {
return new Source(file[0].loc.source.body, filePath);
}

return new Source(file[0], filePath);
});

const document = concatAST(
operationSources.map((source: Source) => {
sanitizedSources.map((source: Source) => {
try {
return parse(source);
} catch (error) {
Expand Down Expand Up @@ -88,17 +105,11 @@ async function getOperationsForProject(
}

return {
ast: compile(schema, document),
ast: compile(schema, document, {addTypename: true}),
config: projectConfig,
};
}

async function loadOperationSource(filePath: string) {
const body = await readFile(filePath, 'utf8');

return new Source(body, filePath);
}

function runForEachFixture<T extends Partial<Evaluation>>(
fixturePaths: string[],
runner: (fixture: Fixture) => T,
Expand All @@ -107,9 +118,15 @@ function runForEachFixture<T extends Partial<Evaluation>>(
fixturePaths.map(async (fixturePath) => {
try {
const fixture = await readJSON(fixturePath);

let fixtureContent = fixture;
if (fixture.data) {
fixtureContent = fixture.data;
}

return {
fixturePath,
...(runner({path: fixturePath, content: fixture}) as any),
...(runner({path: fixturePath, content: fixtureContent}) as any),
};
} catch (error) {
return {
Expand Down
172 changes: 148 additions & 24 deletions packages/graphql-validate-fixtures/src/validate.ts
Expand Up @@ -248,40 +248,164 @@ function validateValueAgainstObjectFieldDescription(
return [];
}

const {fields = [], fragmentSpreads = [], type} = fieldDescription;

const fragmentFields: Field[] = [];

if (fragmentSpreads) {
fragmentSpreads
.map((spread) => ast.fragments[spread])
.forEach((fragment) => {
fragment.fields.forEach((field) => {
if (fields.some(({fieldName}) => fieldName === field.fieldName)) {
return;
}

const isGuaranteedTypeMatch = fragment.possibleTypes.includes(
makeTypeNullable(type),
);
const {
fields: currentValueFields = [],
fragmentSpreads = [],
inlineFragments = [],
type: currentValueType,
} = fieldDescription;

const fragmentSpreadFields: Field[] = [];
const inlineFragmentFields: Field[] = [];

if (fragmentSpreads.length !== 0) {
fragmentSpreadFields.push(
...getFragmentSpreadsFields(
fragmentSpreads,
currentValueFields,
currentValueType,
value,
ast,
),
);
}

fragmentFields.push(
isGuaranteedTypeMatch
? field
: {...field, type: makeTypeNullable(field.type)},
);
});
});
if (inlineFragments.length !== 0) {
inlineFragmentFields.push(
...getInlineFragmentsFields(
inlineFragments,
currentValueFields,
currentValueType,
value,
ast,
),
);
}

return validateValueAgainstFields(
value,
fields.concat(fragmentFields),
currentValueFields.concat(fragmentSpreadFields, inlineFragmentFields),
keyPath,
ast,
);
}

function getInlineFragmentsFields(
inlineFragments: any[],
currentValueFields: any[],
currentValueType,
currentValue: any,
ast: AST,
) {
const inlineFragmentFields: Field[] = [];

inlineFragments
.filter(
(nestedFragment) =>
nestedFragment.typeCondition.name === currentValue.__typename,
)
.forEach((inlineFragment) => {
inlineFragment.fields.forEach((inlineFragmentField: Field) => {
if (isFieldContainedInFields(inlineFragmentField, currentValueFields)) {
return;
}

if (!isFieldContainedInObjectKeys(inlineFragmentField, currentValue)) {
return;
}

const isGuaranteedTypeMatch = inlineFragment.possibleTypes.includes(
makeTypeNullable(currentValueType),
);

inlineFragmentFields.push(
isGuaranteedTypeMatch
? inlineFragmentField
: {
...inlineFragmentField,
type: makeTypeNullable(inlineFragmentField.type),
},
);
});

if (inlineFragment.fragmentSpreads.length !== 0) {
const inlineFragmentFragmentSpreadsFields = getFragmentSpreadsFields(
inlineFragment.fragmentSpreads,
currentValueFields,
currentValueType,
currentValue,
ast,
);

inlineFragmentFragmentSpreadsFields
.filter((fragmentSpreadField) =>
Object.keys(currentValue).includes(fragmentSpreadField.fieldName),
)
.map((fragmentSpreadField) =>
inlineFragmentFields.push(fragmentSpreadField),
);
}
});

return inlineFragmentFields;
}

function getFragmentSpreadsFields(
fragmentSpreads: any[],
currentValueFields: any[],
currentValueType,
currentValue: any,
ast: AST,
): Field[] {
const fragmentSpreadFields: Field[] = [];

fragmentSpreads
.map((spread) => ast.fragments[spread])
.forEach((fragment) => {
fragment.fields.forEach((fragmentField) => {
if (isFieldContainedInFields(fragmentField, currentValueFields)) {
return;
}

const isGuaranteedTypeMatch = fragment.possibleTypes.includes(
makeTypeNullable(currentValueType),
);

fragmentSpreadFields.push(
isGuaranteedTypeMatch
? fragmentField
: {...fragmentField, type: makeTypeNullable(fragmentField.type)},
);
});

if (fragment.fragmentSpreads.length !== 0) {
const nestedFragmentSpreads = fragment.fragmentSpreads.map(
(spread) => ast.fragments[spread],
);

fragmentSpreadFields.push(
...getInlineFragmentsFields(
nestedFragmentSpreads,
currentValueFields,
currentValueType,
currentValue,
ast,
),
);
}
});

return fragmentSpreadFields;
}

function isFieldContainedInObjectKeys(field: Field, value: any) {
return Object.keys(value).some((key) => key === field.fieldName);
}

function isFieldContainedInFields(field: Field, fields: Field[]) {
return fields.some(({fieldName}) => fieldName === field.fieldName);
}

function makeTypeNullable(type: GraphQLType) {
return isNonNullType(type) ? type.ofType : type;
}
Expand Down
Expand Up @@ -17,6 +17,32 @@ exports[`evaluateFixtures() handles ambiguous operation names in multi-project f
]
`;

exports[`evaluateFixtures() handles fixtures and typescript-defined queries without errors 1`] = `
[
{
"fixturePath": "packages/graphql-validate-fixtures/tests/fixtures/typescript-all-clear/fixtures/another-another-fixture.json",
"operationName": "Another",
"operationPath": "packages/graphql-validate-fixtures/tests/fixtures/typescript-all-clear/queries/Another.ts",
"operationType": "query",
"validationErrors": [],
},
{
"fixturePath": "packages/graphql-validate-fixtures/tests/fixtures/typescript-all-clear/fixtures/another-fixture.json",
"operationName": "Another",
"operationPath": "packages/graphql-validate-fixtures/tests/fixtures/typescript-all-clear/queries/Another.ts",
"operationType": "query",
"validationErrors": [],
},
{
"fixturePath": "packages/graphql-validate-fixtures/tests/fixtures/typescript-all-clear/fixtures/MyQuery/fixture.json",
"operationName": "My",
"operationPath": "packages/graphql-validate-fixtures/tests/fixtures/typescript-all-clear/queries/Query.ts",
"operationType": "query",
"validationErrors": [],
},
]
`;

exports[`evaluateFixtures() handles fixtures that are invalid json 1`] = `
[
{
Expand Down
@@ -0,0 +1,4 @@
schemaPath: schema.json
includes:
- schema.json
- queries/**/*.graphql
@@ -0,0 +1,3 @@
{
"name": "Chris"
}
@@ -0,0 +1,4 @@
{
"@operation": "Another",
"name": "Mica"
}
@@ -0,0 +1,4 @@
{
"@operation": "AnotherQuery",
"name": "Chris"
}
@@ -0,0 +1,3 @@
query Another {
name
}
@@ -0,0 +1,3 @@
query My {
name
}