【问题标题】:How to generate GraphQL operations from GraphQL schema如何从 GraphQL 模式生成 GraphQL 操作
【发布时间】:2020-12-05 17:30:21
【问题描述】:

我正在寻找一种在使用 GraphQL 时让开发人员工作流程更高效的方法。

目前,在前端使用graphql-code-generator 从我的 GraphQL 服务器生成类型。

这很好,但这只是生成类型。为了生成突变、查询和订阅的方法,我需要为我的前端项目中的每个操作创建一个 GraphQL 文档,例如:

file addPost.graphql

mutation addPost {
...
}
...

我发现必须创建一个额外的 addPost.graphql 来生成该方法有点多余,因为它已经在我的 GraphQL 服务器上声明了。

是否有一个插件/配置可以生成这些方法,我可以在我的项目中使用而无需手动创建额外的 GraphQL 文档?

这是我的 GraphQL 生成器 yml 文件

# graphql-generator.yml
overwrite: true
schema: https://localhost:8088/query
documents: ./libs/**/*.graphql          <----- generating these *.graphql files would be great! 
generates:
  libs/graphql/src/lib/generated/graphql.ts:
    plugins:
      - "typescript"
      - "typescript-resolvers"
      - "typescript-operations"
      - "typescript-apollo-angular"
  ./graphql.schema.json:
    plugins:
      - "introspection"

【问题讨论】:

    标签: typescript graphql apollo-client graphql-codegen


    【解决方案1】:

    GraphQL 的核心概念之一是允许组件或任何其他消费者选择他们需要的字段,而不是由其他东西为他们决定(后端开发人员/服务器/代码)。

    此外,基于 GraphQL 模式生成操作很棘手 - 由于图的性质,如果没有一组约束(例如:要达到什么嵌套级别?如何处理循环链接),您无法真正生成它?如果出现争论,你会怎么做?如果架构发生变化怎么办?等等)

    GraphQL 代码生成器没有这样做,因为我们认为使用 GraphQL 层的开发人员应该决定字段。

    在我们开发的其他一些解决方案中,我们需要这样的工具来生成选择集,但有一些预定义的约束。此 cmets 对其进行求和并提供用于生成这些的代码示例:https://github.com/dotansimha/graphql-code-generator/discussions/2349#discussioncomment-15754

    如果您愿意,您可以将它们生成到文件中,然后将其提供给 codegen,或者您可以在项目中创建自定义文档加载器以动态创建它 (https://graphql-code-generator.com/docs/getting-started/documents-field#custom-document-loader)

    【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2019-09-08
    • 2020-10-16
    • 2023-04-01
    • 2020-01-15
    • 2019-04-20
    • 2021-01-08
    • 2020-05-17
    • 2020-05-28
    相关资源
    最近更新 更多