gqlQuery.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Ref } from "@nuxtjs/composition-api"
  2. import {
  3. GraphQLError,
  4. GraphQLSchema,
  5. parse as gqlParse,
  6. validate as gqlValidate,
  7. } from "graphql"
  8. import { LinterDefinition, LinterResult } from "./linter"
  9. /**
  10. * Creates a Linter function that can lint a GQL query against a given
  11. * schema
  12. */
  13. export const createGQLQueryLinter: (
  14. schema: Ref<GraphQLSchema | null>
  15. ) => LinterDefinition = (schema: Ref<GraphQLSchema | null>) => (text) => {
  16. if (text === "") return Promise.resolve([])
  17. if (!schema.value) return Promise.resolve([])
  18. try {
  19. const doc = gqlParse(text)
  20. const results = gqlValidate(schema.value, doc).map(
  21. ({ locations, message }) =>
  22. <LinterResult>{
  23. from: {
  24. line: locations![0].line - 1,
  25. ch: locations![0].column - 1,
  26. },
  27. to: {
  28. line: locations![0].line - 1,
  29. ch: locations![0].column,
  30. },
  31. message,
  32. severity: "error",
  33. }
  34. )
  35. return Promise.resolve(results)
  36. } catch (e) {
  37. const err = e as GraphQLError
  38. return Promise.resolve([
  39. <LinterResult>{
  40. from: {
  41. line: err.locations![0].line - 1,
  42. ch: err.locations![0].column - 1,
  43. },
  44. to: {
  45. line: err.locations![0].line - 1,
  46. ch: err.locations![0].column,
  47. },
  48. message: err.message,
  49. severity: "error",
  50. },
  51. ])
  52. }
  53. }