【问题标题】:How to modularize GraphQL schema when using `buildSchema`?使用`buildSchema`时如何模块化GraphQL模式?
【发布时间】:2017-09-28 10:57:41
【问题描述】:

自从我更新我的 graphql-js 依赖项以来已经有一年了。我现在看到有一个简化模式生成的实用程序:buildSchema。此函数将 GraphQL 语言中的整个模式作为字符串作为参数。太棒了,但是有没有办法模块化呢?我的架构不是超级小,而且会很糟糕地塞进一个 .graphql 文件中。例如,是否有某种实用程序或模式可以将每个类型定义存储在其自己的文件中?

【问题讨论】:

标签: graphql


【解决方案1】:

如果你有 graphql-tools 包,你可以使用 makeExecutableSchema 像这样模块化你的架构:

const schema = makeExecutableSchema({
    typeDefs: [schema1, schema2, schema3, ...],
    resolvers: resolvers,
});

这样,每种类型都可以在自己的文件中定义。

【讨论】:

【解决方案2】:

您可以使用merge-graphql-schemas 包进一步提高您的架构模块化。

这是一个模块化的 graphql 服务器种子 - graphql-server-seed

项目结构允许您将类型和解析器分离到多个文件中。希望对您有所帮助!

【讨论】:

    【解决方案3】:

    如果您使用的是 Apollo 的 graphql-tools,那么我发现构建架构的最佳方法是使用 schemaglue.js(免责声明:我已经构建了这个):

    const { makeExecutableSchema } = require('graphql-tools')
    const { glue } = require('schemaglue')
    
    const { schema, resolver } = glue('src/graphql')
    
    const executableSchema = makeExecutableSchema({
        typeDefs: schema,
        resolvers: resolver
    })
    

    然后你就可以用类似的东西来构建你的架构和解析器了:

    - src/
       |__ graphql/
              |__ product/
              |       |__ schema.js
              |       |__ resolver.js
              |
              |__ variant/
                      |__ schema.js
                      |__ resolver.js
    
    - index.js
    - package.json
    

    我已经写了一篇关于这个here的详细文章。

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 2017-11-29
      • 2018-12-14
      • 2020-05-09
      • 2019-07-17
      • 1970-01-01
      • 2014-10-18
      • 2020-09-07
      • 2022-08-18
      相关资源
      最近更新 更多