【问题标题】:How does one set up (database, or other) context in a GraphQL resolver?如何在 GraphQL 解析器中设置(数据库或其他)上下文?
【发布时间】:2017-10-28 11:17:33
【问题描述】:

GraphQL 文档 give an example 的解析器函数接受称为“上下文”的参数。

他们必须这样说 -

context 提供给每个解析器的值,其中包含重要的上下文信息,例如当前登录的用户或对数据库的访问。

他们的代码示例看起来像这样 -

Query: {
  human(obj, args, context) {
    return context.db.loadHumanByID(args.id).then(
      userData => new Human(userData)
    )
  }
}

在我看来,希望在解析器函数中访问数据库是一种非常自然的模式,不出所料,这是我需要做的。

显然,此数据库上下文不是自动设置的,因为 GraphQL 完全不知道您的特定数据持久性方式。

我的问题是,如何配置此上下文以提供特定的数据库接口?我在教程/文档或任何地方都找不到提及这一点。

【问题讨论】:

    标签: node.js graphql


    【解决方案1】:

    上下文是在您设置服务器时定义的。我在文档中也看不到。

    graphqlExpress(req => {
      return {
        schema: makeExecutableSchema({
          typeDefs: schema.ast,
          resolvers,
          logger
        }),
        context: {
          db: mongodb.MongoClient.connect(...)
        }
      };
    })
    

    【讨论】:

      【解决方案2】:

      您可以在调用graphql 函数时将上下文传递给graphql。
      它被指定为here

      这里是graphql函数的流定义:

      graphql(
        schema: GraphQLSchema,
        requestString: string,
        rootValue?: ?any,
        contextValue?: ?any, // Arbitrary context
        variableValues?: ?{[key: string]: any},
        operationName?: ?string
      ): Promise<GraphQLResult>
      

      【讨论】:

        猜你喜欢
        • 2011-12-12
        • 2020-07-26
        • 1970-01-01
        • 2023-02-03
        • 2021-06-17
        • 2017-05-16
        • 1970-01-01
        • 2012-03-04
        • 2017-05-04
        相关资源
        最近更新 更多