Как обработать схему graphql-codegen со строковыми шаблонами в typScript / javascript export - PullRequest
1 голос
/ 28 февраля 2020

Я использую graphql-codegen для генерации файлов типов машин для данной схемы.

Все хорошо, кроме случаев, когда в экспортированной схеме есть шаблон строки, он будет жаловаться на синтаксис и, кажется, не будет его компилировать , Проверьте следующие файлы для получения более подробной информации.

Ниже указано types.js:

const gql = require("graphql-tag");

const Colors = ["Red", "Yellow"];
export default gql`
  type Person {
    name: String
  }
  enum Color {
      ${Colors.join("\n")}
  }
# if we change the above enum to be the below, it will be good
#   enum Color {
#       Red
#       Yellow
#   }
`;

И файл конфигурации yml:

schema: 
  - types.js

generates:
  generated.ts:
    plugins:
        - typescript
        - typescript-resolvers

При запуске yarn graphql:codegen жалуется на следующее:

Found 1 error

  ✖ generated.ts
    Failed to load schema from types.js:

        Syntax Error: Expected Name, found }
        GraphQLError: Syntax Error: Expected Name, found }
    at syntaxError (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/error/syntaxError.js:15:10)
    at Parser.expectToken (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1404:40)
    at Parser.parseName (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:94:22)
    at Parser.parseEnumValueDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1014:21)
    at Parser.optionalMany (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1497:28)
    at Parser.parseEnumValuesDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1002:17)
    at Parser.parseEnumTypeDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:986:23)
    at Parser.parseTypeSystemDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:705:23)
    at Parser.parseDefinition (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:146:23)
    at Parser.many (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:1518:26)
    at Parser.parseDocument (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:111:25)
    at Object.parse (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/graphql/language/parser.js:36:17)
    at Object.parseGraphQLSDL (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/@graphql-toolkit/common/index.cjs.js:572:28)
    at CodeFileLoader.load (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/@graphql-toolkit/code-file-loader/index.cjs.js:120:31)
    at async /Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/@graphql-toolkit/core/index.cjs.js:682:25
    at async Promise.all (index 0)

        GraphQL Code Generator supports:
          - ES Modules and CommonJS exports (export as default or named export "schema")
          - Introspection JSON File
          - URL of GraphQL endpoint
          - Multiple files with type definitions (glob expression)
          - String in config file

        Try to use one of above options and run codegen again.
    Error: Failed to load schema
        at loadSchema (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/@graphql-codegen/cli/bin.js:353:15)
    Error: Failed to load schema
        at loadSchema (/Users/rliu/study/reproduce-graphql-codegen-with-string-template-in-js-export/node_modules/@graphql-codegen/cli/bin.js:353:15)

Похоже, graphql-codegen не понравилась строка шаблона, например: ${Colors.join('\n')}.

Также, пожалуйста, ознакомьтесь с репо , содержащим все вышеуказанные файлы.

Кто-нибудь может помочь исправить? Спасибо.

1 Ответ

0 голосов
/ 23 марта 2020

Это не обрабатывается, в основном из-за сложности загрузки файлов кода и интерполяции. Но способ обойти это:

  • Создайте один schema.js файл.
  • Импортируйте все typedefs с интерполяцией строк из ваших исходных файлов и используйте buildSchema (из graphql) или makeExecutableSchema (из graphql-tools), чтобы создать экземпляр объекта GraphQLSchema.
  • Экспортируйте GraphQLSchema в качестве экспорта по умолчанию или в качестве идентификатора с именем schema.
  • Предоставьте этот файл в codegen (выполнив schema: ./schema.js - использование одного файла кода приводит к тому, что codegen найдите код ast, а затем попытайтесь выполнить require.

Если вы используете TypeScript, вам также следует добавить расширение require к кодексу (см. https://graphql-code-generator.com/docs/getting-started/require-field#typescript -поддержка )

...