【问题标题】:How can I make `apollo server` to work with graphql schemaObject?如何使“apollo 服务器”与 graphql schemaObject 一起使用?
【发布时间】:2020-03-27 15:00:22
【问题描述】:

我在 nodejs 项目中使用 express-graphql 来实现 graphql。我的架构有以下定义。但是,我最近切换到apollo,但我不知道如何让apolloGraphQLObjectType 一样接受graphql schemaObject

下面是我的schemaObject

var graphql = require('graphql');

var fakeDatabase = {
  'a': {
    id: 'a',
    name: 'alice',
  },
  'b': {
    id: 'b',
    name: 'bob',
  },
};

// Define the User type
var userType = new GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: GraphQLString },
    name: { type: GraphQLString },
  }
});

// Define the Query type
var queryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: userType,
      // `args` describes the arguments that the `user` query accepts
      args: {
        id: { type: GraphQLString }
      },
      resolve: (_, {id}) => {
        return fakeDatabase[id];
      }
    }
  }
});

const graphqlSchema = new GraphQLSchema({ query: queryType });

apollo 中,我的这段代码不起作用。可能是因为我不能在typeDefs 上使用graphqlSchema 来代替ApolloServer。我想知道我怎样才能让它工作。我需要将其转换为其他格式吗?我真的不想更改我的架构对象。

const server = new ApolloServer({
  typeDefs: graphqlSchema,
  resolvers
})

【问题讨论】:

    标签: node.js graphql apollo


    【解决方案1】:

    docs 所示,ApolloServer 构造函数接受一个schema 参数,可以用来代替typeDefsresolvers。架构必须是 GraphQLSchema 的实例。

    const schema = new GraphQLSchema({ ... })
    const server = new ApolloServer({ schema })
    

    请注意,如果您使用的是 Upload 标量,则必须手动将其添加到您的架构中(如果您提供 typeDefs,则为您完成此操作。

    【讨论】:

    • upload scalar 是什么意思?
    • here。如果您不使用文件上传,则可以忽略该注释。就此而言,如果您以编程方式构建架构,那么无论如何这都不适用于您。但为了完整起见,我想我会提到它,因为它是一个常见的问题。
    • 我看到上面写着An executable GraphQL schema that will override the typeDefs and resolvers provided。我不明白为什么它会覆盖resolversresolversschema 的一部分吗?
    • 是的。解析器是类似于示例代码中的 resolve 函数的函数。如果您要提供类型定义,它们将不包含任何实际代码,因此我们必须单独传递它们。在底层,ApolloServer 接受类型定义和解析器,并将它们转换为可执行模式。但是,如果您已经为其提供了可执行模式,则无需传入类型定义或解析器。
    【解决方案2】:

    经过一番搜索和调试,可以printSchema完成。所以下面是代码

    const { printSchema } = require('graphql')
    const server = new ApolloServer({
      typeDefs: printSchema(graphqlSchema),
      resolvers
    })
    

    【讨论】:

    • 这将导致定义为架构一部分的任何解析器丢失。
    猜你喜欢
    • 2017-11-11
    • 2018-02-23
    • 2020-07-07
    • 1970-01-01
    • 2021-12-01
    • 2023-03-23
    • 2019-12-18
    • 2021-03-29
    • 2017-05-06
    相关资源
    最近更新 更多