Skip to content

Instantly share code, notes, and snippets.

@Quramy
Created March 21, 2017 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Quramy/7aa3831c5d9e96e3e57961f56655b586 to your computer and use it in GitHub Desktop.
Save Quramy/7aa3831c5d9e96e3e57961f56655b586 to your computer and use it in GitHub Desktop.
TS 2.3 Language Service Plugin for completion GraphQL Query
import * as ts from 'typescript/lib/tsserverlibrary';
const { buildClientSchema } = require('graphql');
const { getAutocompleteSuggestions } = require('graphql-language-service-interface');
// TODO replace the result by introspection query
const introspectionJson = require('../schema.json');
const schema = buildClientSchema(introspectionJson.data);
function findNode(sourceFile: ts.SourceFile, position: number): ts.Node | undefined {
function find(node: ts.Node): ts.Node|undefined {
if (position >= node.getStart() && position < node.getEnd()) {
return ts.forEachChild(node, find) || node;
}
}
return find(sourceFile);
}
function create(info: ts.server.PluginCreateInfo): ts.LanguageService {
const delegate = info.languageService.getCompletionsAtPosition;
info.languageService.getCompletionsAtPosition = function(fileName: string, position: number) {
const sourceFile = info.languageService.getProgram().getSourceFile(fileName);
const node = findNode(sourceFile, position);
if (!node || node.kind !== ts.SyntaxKind.NoSubstitutionTemplateLiteral) {
return delegate(fileName, position);
}
const cursor = node.getStart() - position;
const text = node.getText();
const rawResults = getAutocompleteSuggestions(schema, text, cursor, '') as { label: string }[];
const result: ts.CompletionInfo = {
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: false,
entries: rawResults.map(r => {
return {
name: r.label,
kindModifiers: 'declare',
kind: 'var',
sortText: '0',
};
}),
};
return result;
};
return info.languageService;
}
module.exports = function pluginModuleFactory() {
return { create: create };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment