~/Projects/hoppscotch
git clone https://code.lsong.org/hoppscotch
Commit
- Commit
- 0c2cec46a7289b445f65cdec013bf9a31b43b94c
- Author
- Andrew Bastin <[email protected]>
- Date
- 2021-09-06 23:30:43 +0530 +0530
- Diffstat
helpers/editor/linting/gqlQuery.ts | 58 ++++++++++++++++++++++++++++++++
feat: implement gql query linting in codemirror
diff --git a/helpers/editor/linting/gqlQuery.ts b/helpers/editor/linting/gqlQuery.ts new file mode 100644 index 0000000000000000000000000000000000000000..648cfa732db1b03be104597a199e3aea2f3fe330 --- /dev/null +++ b/helpers/editor/linting/gqlQuery.ts @@ -0,0 +1,58 @@ +import { Ref } from "@nuxtjs/composition-api" +import { + GraphQLError, + GraphQLSchema, + parse as gqlParse, + validate as gqlValidate, +} from "graphql" +import { LinterDefinition, LinterResult } from "./linter" + +/** + * Creates a Linter function that can lint a GQL query against a given + * schema + */ +export const createGQLQueryLinter: ( + schema: Ref<GraphQLSchema | null> +) => LinterDefinition = (schema: Ref<GraphQLSchema | null>) => (text) => { + if (text === "") return Promise.resolve([]) + if (!schema.value) return Promise.resolve([]) + + try { + const doc = gqlParse(text) + + const results = gqlValidate(schema.value, doc).map( + ({ locations, message }) => + <LinterResult>{ + from: { + line: locations![0].line - 1, + ch: locations![0].column - 1, + }, + to: { + line: locations![0].line - 1, + ch: locations![0].column, + }, + message, + severity: "error", + } + ) + + return Promise.resolve(results) + } catch (e) { + const err = e as GraphQLError + + return Promise.resolve([ + <LinterResult>{ + from: { + line: err.locations![0].line - 1, + ch: err.locations![0].column - 1, + }, + to: { + line: err.locations![0].line - 1, + ch: err.locations![0].column, + }, + message: err.message, + severity: "error", + }, + ]) + } +}