首页 文章

如何在GraphQL解析器中设置(数据库或其他)上下文?

提问于
浏览
3

GraphQL docs give an example是一个解析器函数,它接受一个名为"context"的参数 .

他们不得不这样说 -

context(上下文)提供给每个解析程序并保存重要上下文信息(如当前登录用户或访问数据库)的值 .

他们的代码示例如下所示 -

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

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

显然,这个数据库上下文不会自动设置,因为GraphQL完全不了解您的特定数据持久性方法 .

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

2 回答

  • 4

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

    以下是 graphql 函数的流程定义:

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

    设置服务器时定义上下文 . 我也无法在文档中看到它 .

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

相关问题