Skip to content
This repository was archived by the owner on Sep 2, 2020. It is now read-only.

Go to definition for named types #233

Closed
wants to merge 11 commits into from
Closed
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Currently supported features include:
- Diagnostics (GraphQL syntax linting/validations) (**spec-compliant**)
- Autocomplete suggestions (**spec-compliant**)
- Hyperlink to fragment definitions (**spec-compliant**)
- Hyperlink to named types (type, input, enum) definitions (**spec-compliant**)
- Outline view support for queries


Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,6 @@
"graphql-language-service-utils": "^1.0.0-0",
"lerna": "^2.0.0",
"mocha": "4.1.0",
"prettier": "^1.5.3"
"prettier": "1.13"
}
}
56 changes: 56 additions & 0 deletions packages/interface/src/GraphQLLanguageService.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import type {
FragmentSpreadNode,
FragmentDefinitionNode,
OperationDefinitionNode,
TypeDefinitionNode,
NamedTypeNode,
} from 'graphql';
import type {
CompletionItem,
Expand Down Expand Up @@ -43,6 +45,7 @@ import {
DIRECTIVE_DEFINITION,
FRAGMENT_SPREAD,
OPERATION_DEFINITION,
NAMED_TYPE,
} from 'graphql/language/kinds';

import {parse, print} from 'graphql';
Expand All @@ -52,6 +55,7 @@ import {validateQuery, getRange, SEVERITY} from './getDiagnostics';
import {
getDefinitionQueryResultForFragmentSpread,
getDefinitionQueryResultForDefinitionNode,
getDefinitionQueryResultForNamedType,
} from './getDefinition';
import {getASTNodeAtPosition} from 'graphql-language-service-utils';

Expand Down Expand Up @@ -224,11 +228,63 @@ export class GraphQLLanguageService {
query,
(node: FragmentDefinitionNode | OperationDefinitionNode),
);
case NAMED_TYPE:
return this._getDefinitionForNamedType(
query,
ast,
node,
filePath,
projectConfig,
);
}
}
return null;
}

async _getDefinitionForNamedType(
query: string,
ast: DocumentNode,
node: NamedTypeNode,
filePath: Uri,
projectConfig: GraphQLProjectConfig,
): Promise<?DefinitionQueryResult> {
const objectTypeDefinitions = await this._graphQLCache.getObjectTypeDefinitions(
projectConfig,
);

const dependencies = await this._graphQLCache.getObjectTypeDependenciesForAST(
ast,
objectTypeDefinitions,
);

const localObjectTypeDefinitions = ast.definitions.filter(
definition =>
definition.kind === OBJECT_TYPE_DEFINITION ||
definition.kind === INPUT_OBJECT_TYPE_DEFINITION ||
definition.kind === ENUM_TYPE_DEFINITION,
);

const typeCastedDefs = ((localObjectTypeDefinitions: any): Array<
TypeDefinitionNode,
>);

const localOperationDefinationInfos = typeCastedDefs.map(
(definition: TypeDefinitionNode) => ({
filePath,
content: query,
definition,
}),
);

const result = await getDefinitionQueryResultForNamedType(
query,
node,
dependencies.concat(localOperationDefinationInfos),
);

return result;
}

async _getDefinitionForFragmentSpread(
query: string,
ast: DocumentNode,
Expand Down
50 changes: 48 additions & 2 deletions packages/interface/src/__tests__/GraphQLLanguageService-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,51 @@ import {GraphQLConfig} from 'graphql-config';
import {GraphQLLanguageService} from '../GraphQLLanguageService';

const MOCK_CONFIG = {
includes: ['./queries/**'],
schemaPath: './__schema__/StarWarsSchema.graphql',
includes: ['./queries/**', '**/*.graphql'],
};

describe('GraphQLLanguageService', () => {
const mockCache: any = {
getGraphQLConfig() {
return new GraphQLConfig(MOCK_CONFIG, join(__dirname, '.graphqlconfig'));
},

getObjectTypeDefinitions() {
return {
Episode: {
filePath: 'fake file path',
content: 'fake file content',
definition: {
name: {
value: 'Episode',
},
loc: {
start: 293,
end: 335,
},
},
},
};
},

getObjectTypeDependenciesForAST() {
return [
{
filePath: 'fake file path',
content: 'fake file content',
definition: {
name: {
value: 'Episode',
},
loc: {
start: 293,
end: 335,
},
},
},
];
},
};

let languageService;
Expand All @@ -33,9 +70,18 @@ describe('GraphQLLanguageService', () => {

it('runs diagnostic service as expected', async () => {
const diagnostics = await languageService.getDiagnostics(
'qeury',
'query',
'./queries/testQuery.graphql',
);
expect(diagnostics.length).to.equal(1);
});

it('runs definition service as expected', async () => {
const definitionQueryResult = await languageService.getDefinition(
'type Query { hero(episode: Episode): Character }',
{line: 0, character: 28},
'./queries/definitionQuery.graphql',
);
expect(definitionQueryResult.definitions.length).to.equal(1);
});
});
41 changes: 39 additions & 2 deletions packages/interface/src/__tests__/getDefinition-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,46 @@
import {expect} from 'chai';
import {describe, it} from 'mocha';
import {parse} from 'graphql';
import {getDefinitionQueryResultForFragmentSpread} from '../getDefinition';
import {
getDefinitionQueryResultForFragmentSpread,
getDefinitionQueryResultForNamedType,
} from '../getDefinition';

describe('getDefinition', () => {
describe('getDefinitionQueryResultForNamedType', () => {
it('returns correct Position', async () => {
const query = `type Query {
hero(episode: Episode): Character
}

type Episode {
id: ID!
}
`;
const parsedQuery = parse(query);
const namedTypeDefinition = parsedQuery.definitions[0].fields[0].type;

const result = await getDefinitionQueryResultForNamedType(
query,
{
...namedTypeDefinition,
},
[
{
file: 'someFile',
content: query,
definition: {
...namedTypeDefinition,
},
},
],
);
expect(result.definitions.length).to.equal(1);
expect(result.definitions[0].position.line).to.equal(1);
expect(result.definitions[0].position.character).to.equal(32);
});
});

describe('getDefinitionQueryResultForFragmentSpread', () => {
it('returns correct Position', async () => {
const query = `query A {
Expand All @@ -39,7 +76,7 @@ describe('getDefinition', () => {
);
expect(result.definitions.length).to.equal(1);
expect(result.definitions[0].position.line).to.equal(1);
expect(result.definitions[0].position.character).to.equal(15);
expect(result.definitions[0].position.character).to.equal(6);
});
});
});
35 changes: 35 additions & 0 deletions packages/interface/src/__tests__/getDiagnostics-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,41 @@ describe('getDiagnostics', () => {
expect(error.source).to.equal('GraphQL: Deprecation');
});

it('returns no errors for valid query', () => {
const errors = getDiagnostics('query { hero { name } }', schema);
expect(errors.length).to.equal(0);
});

it('returns no errors for valid query', () => {
const errors = getDiagnostics('query { hero { name } }', schema);
expect(errors.length).to.equal(0);
});

it('returns no errors for valid query with aliases', () => {
const errors = getDiagnostics(
'query { superHero: hero { superName :name } }',
schema,
);
expect(errors.length).to.equal(0);
});

it('catches a syntax error in the SDL', () => {
const errors = getDiagnostics(
`
type Human implements Character {
SyntaxError
id: String!
}
`,
schema,
);
expect(errors.length).to.equal(1);
const error = errors[0];
expect(error.message).to.equal('Syntax Error: Expected :, found Name "id"');
expect(error.severity).to.equal(SEVERITY.ERROR);
expect(error.source).to.equal('GraphQL: Syntax');
});

// TODO: change this kitchen sink to depend on the local schema
// and then run diagnostics with the schema
it('returns no errors after parsing kitchen-sink query', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
type Query { hero(episode: Episode): Character }
5 changes: 3 additions & 2 deletions packages/interface/src/getAutocompleteSuggestions.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,8 +304,9 @@ function getSuggestionsForFragmentSpread(
relevantFrags.map(frag => ({
label: frag.name.value,
detail: String(typeMap[frag.typeCondition.name.value]),
documentation: `fragment ${frag.name.value} on ${frag.typeCondition.name
.value}`,
documentation: `fragment ${frag.name.value} on ${
frag.typeCondition.name.value
}`,
})),
);
}
Expand Down
53 changes: 48 additions & 5 deletions packages/interface/src/getDefinition.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import type {
FragmentSpreadNode,
FragmentDefinitionNode,
OperationDefinitionNode,
NamedTypeNode,
TypeDefinitionNode,
} from 'graphql';
import type {
Definition,
Expand All @@ -21,6 +23,7 @@ import type {
Position,
Range,
Uri,
ObjectTypeInfo,
} from 'graphql-language-service-types';
import {locToRange, offsetToPosition} from 'graphql-language-service-utils';
import invariant from 'assert';
Expand All @@ -39,6 +42,29 @@ function getPosition(text: string, node: ASTNode): Position {
return offsetToPosition(text, location.start);
}

export async function getDefinitionQueryResultForNamedType(
text: string,
node: NamedTypeNode,
dependencies: Array<ObjectTypeInfo>,
): Promise<DefinitionQueryResult> {
const name = node.name.value;
const defNodes = dependencies.filter(
({definition}) => definition.name && definition.name.value === name,
);
if (defNodes.length === 0) {
process.stderr.write(`Definition not found for GraphQL type ${name}`);
return {queryRange: [], definitions: []};
}
const definitions: Array<Definition> = defNodes.map(
({filePath, content, definition}) =>
getDefinitionForNodeDefinition(filePath || '', content, definition),
);
return {
definitions,
queryRange: definitions.map(_ => getRange(text, node)),
};
}

export async function getDefinitionQueryResultForFragmentSpread(
text: string,
fragment: FragmentSpreadNode,
Expand All @@ -52,10 +78,9 @@ export async function getDefinitionQueryResultForFragmentSpread(
process.stderr.write(`Definition not found for GraphQL fragment ${name}`);
return {queryRange: [], definitions: []};
}
const definitions: Array<
Definition,
> = defNodes.map(({filePath, content, definition}) =>
getDefinitionForFragmentDefinition(filePath || '', content, definition),
const definitions: Array<Definition> = defNodes.map(
({filePath, content, definition}) =>
getDefinitionForFragmentDefinition(filePath || '', content, definition),
);
return {
definitions,
Expand Down Expand Up @@ -83,7 +108,25 @@ function getDefinitionForFragmentDefinition(
invariant(name, 'Expected ASTNode to have a Name.');
return {
path,
position: getPosition(text, name),
position: getPosition(text, definition),
range: getRange(text, definition),
name: name.value || '',
language: LANGUAGE,
// This is a file inside the project root, good enough for now
projectRoot: path,
};
}

function getDefinitionForNodeDefinition(
path: Uri,
text: string,
definition: TypeDefinitionNode,
): Definition {
const name = definition.name;
invariant(name, 'Expected ASTNode to have a Name.');
return {
path,
position: getPosition(text, definition),
range: getRange(text, definition),
name: name.value || '',
language: LANGUAGE,
Expand Down
4 changes: 3 additions & 1 deletion packages/interface/src/getDiagnostics.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ function annotations(
const highlightNode =
node.kind !== 'Variable' && node.name
? node.name
: node.variable ? node.variable : node;
: node.variable
? node.variable
: node;

invariant(error.locations, 'GraphQL validation error requires locations.');
const loc = error.locations[0];
Expand Down
Loading