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

Share validation logic between CLI and language server #506

Merged
merged 2 commits into from
Jul 20, 2018
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
18 changes: 18 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"version": "0.2.0",
// List of configurations. Add new configurations or edit existing ones.
"configurations": [
{
"name": "Launch Apollo VSCode",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}/packages/apollo-vscode"
],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": ["${workspaceRoot}/packages/apollo-vscode/lib/**/*.js"]
}
]
}
53 changes: 42 additions & 11 deletions packages/apollo-cli/src/validation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
validate,
specifiedRules,
NoUnusedFragmentsRule,
KnownDirectivesRule,
Expand All @@ -9,34 +8,66 @@ import {
GraphQLSchema,
DocumentNode,
OperationDefinitionNode,
TypeInfo
} from 'graphql';
TypeInfo,
FragmentDefinitionNode,
visit,
visitWithTypeInfo,
visitInParallel
} from "graphql";

import { ToolError, logError } from 'apollo-codegen-core/lib/errors';
import { ToolError, logError } from "apollo-codegen-core/lib/errors";

export function validateQueryDocument(schema: GraphQLSchema, document: DocumentNode, typeInfo?: TypeInfo) {
const specifiedRulesToBeRemoved = [NoUnusedFragmentsRule, KnownDirectivesRule];
export function getValidationErrors(
schema: GraphQLSchema,
document: DocumentNode,
fragments?: { [fragmentName: string]: FragmentDefinitionNode }
) {
const specifiedRulesToBeRemoved = [
NoUnusedFragmentsRule,
KnownDirectivesRule
];

const rules = [
NoAnonymousQueries,
NoTypenameAlias,
...specifiedRules.filter(rule => !specifiedRulesToBeRemoved.includes(rule))
];

const validationErrors = validate(schema, document, rules, typeInfo);
const typeInfo = new TypeInfo(schema);
const context = new ValidationContext(schema, document, typeInfo);

if (fragments) {
(context as any)._fragments = fragments;
}

const visitors = rules.map(rule => rule(context));
// Visit the whole document with each instance of all provided rules.
visit(document, visitWithTypeInfo(typeInfo, visitInParallel(visitors)));
return context.getErrors();
}

export function validateQueryDocument(
schema: GraphQLSchema,
document: DocumentNode
) {
const validationErrors = getValidationErrors(schema, document);
if (validationErrors && validationErrors.length > 0) {
for (const error of validationErrors) {
logError(error);
}
throw new ToolError('Validation of GraphQL query document failed');
throw new ToolError("Validation of GraphQL query document failed");
}
}

export function NoAnonymousQueries(context: ValidationContext) {
return {
OperationDefinition(node: OperationDefinitionNode) {
if (!node.name) {
context.reportError(new GraphQLError('Apollo does not support anonymous operations', [node]));
context.reportError(
new GraphQLError("Apollo does not support anonymous operations", [
node
])
);
}
return false;
}
Expand All @@ -47,10 +78,10 @@ export function NoTypenameAlias(context: ValidationContext) {
return {
Field(node: FieldNode) {
const aliasName = node.alias && node.alias.value;
if (aliasName == '__typename') {
if (aliasName == "__typename") {
context.reportError(
new GraphQLError(
'Apollo needs to be able to insert __typename when needed, please do not use it as an alias',
"Apollo needs to be able to insert __typename when needed, please do not use it as an alias",
[node]
)
);
Expand Down
40 changes: 4 additions & 36 deletions packages/apollo-language-server/src/diagnostics.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
import {
GraphQLSchema,
TypeInfo,
DocumentNode,
GraphQLError,
visit,
visitWithTypeInfo,
visitInParallel,
ValidationContext,
specifiedRules,
FragmentDefinitionNode,
NoUnusedFragmentsRule,
findDeprecatedUsages
} from "graphql";

Expand All @@ -19,18 +11,19 @@ import { GraphQLDocument } from "./document";
import { highlightNodeForNode } from "./utilities/graphql";
import { rangeForASTNode } from "./utilities/source";

import { getValidationErrors } from "apollo/lib/validation";

export function collectDiagnostics(
schema: GraphQLSchema,
queryDocument: GraphQLDocument,
fragments: { [fragmentName: string]: FragmentDefinitionNode },
customRules: ValidationRule[] = []
fragments: { [fragmentName: string]: FragmentDefinitionNode }
): Diagnostic[] {
const ast = queryDocument.ast;
if (!ast) return queryDocument.syntaxErrors;

const diagnostics = [];

for (const error of validate(schema, ast, fragments, customRules)) {
for (const error of getValidationErrors(schema, ast, fragments)) {
diagnostics.push(
...diagnosticsFromError(error, DiagnosticSeverity.Error, "Validation")
);
Expand Down Expand Up @@ -63,28 +56,3 @@ function diagnosticsFromError(
};
});
}

type ValidationRule = (context: ValidationContext) => any;

// This is a modified version of the corresponding function in graphql-js,
// that allows us to pass in fragments without making these part of the document to be validated.
export function validate(
schema: GraphQLSchema,
documentAST: DocumentNode,
fragments: { [fragmentName: string]: FragmentDefinitionNode },
customRules: ValidationRule[] = []
): ReadonlyArray<GraphQLError> {
const rulesToSkip = [NoUnusedFragmentsRule];
const rules = [
...specifiedRules.filter(rule => !rulesToSkip.includes(rule)),
...customRules
];

const typeInfo = new TypeInfo(schema);
const context = new ValidationContext(schema, documentAST, typeInfo);
(context as any)._fragments = fragments;
const visitors = rules.map(rule => rule(context));
// Visit the whole document with each instance of all provided rules.
visit(documentAST, visitWithTypeInfo(typeInfo, visitInParallel(visitors)));
return context.getErrors();
}