如何将变量附加到 Graphql 上下文?

How to attach variables to the Graphql context?

我正在使用 express-graphql。 我想将一些参数附加到上下文,但它们没有附加。

中间件:

  app.use(graphqlHTTP({
  schema: schema,
  rootValue: resolver,
  graphiql: true,
  context: {someValue: 100}
}))

架构:

type Query {
  get_number: Int!
}

解析器:

get_number(_, __, context) {
 console.log(context);
 return context.someValue;
}

当我尝试调用 get_number 时,它说:

    {
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Query.get_number.",
      "locations": [
        {
          "line": 2,
          "column": 2
        }
      ],
      "path": [
        "get_number"
      ]
    }
  ],
  "data": null
}

console.log(上下文)是这样说的:

{
  fieldName: 'get_number',
  fieldNodes: [
    {
      kind: 'Field',
      alias: undefined,
      name: [Object],
      arguments: [],
      directives: [],
      selectionSet: undefined,
      loc: [Object]
    }
  ],
  returnType: Int!,
  parentType: Query,
  path: { prev: undefined, key: 'get_number' },
  schema: GraphQLSchema {
    __validationErrors: [],
    __allowedLegacyNames: [],
    _queryType: Query,
    _mutationType: Mutation,
    _subscriptionType: undefined,
    _directives: [ @skip, @include, @deprecated ],
    astNode: undefined,
    extensionASTNodes: undefined,
    _typeMap: [Object: null prototype] {
      Query: Query,
      TestType: TestType,
      Int: Int,
      User: User,
      String: String,
      Float: Float,
      ClassMatein: ClassMatein,
      ClassMate: ClassMate,
      Mutation: Mutation,
      UserInput: UserInput,
      __Schema: __Schema,
      __Type: __Type,
      __TypeKind: __TypeKind,
      Boolean: Boolean,
      __Field: __Field,
      __InputValue: __InputValue,
      __EnumValue: __EnumValue,
      __Directive: __Directive,
      __DirectiveLocation: __DirectiveLocation
    },
    _possibleTypeMap: [Object: null prototype] {},
    _implementations: [Object: null prototype] {}
  },
  fragments: [Object: null prototype] {},
  rootValue: {
    test: [Function: test],
    random: [Function: random],
    addTestUser: [Function: addTestUser],
    get_mate: [Function: get_mate],
    get_number: [Function: get_number]
  },
  operation: {
    kind: 'OperationDefinition',
    operation: 'query',
    name: undefined,
    variableDefinitions: [],
    directives: [],
    selectionSet: { kind: 'SelectionSet', selections: [Array], loc: [Object] },
    loc: { start: 0, end: 21 }
  },
  variableValues: {}
}

我的架构:

const {
  buildSchema
} = require('graphql')
const gql = require('graphql-tag');

module.exports = buildSchema(`
  type User {
    name: String!
    email: String!
    age: Int!
  }

我想我的 someValue 应该在 variableValues 中,但它不在那里:( 我应该怎么做才能将此变量(someValue)附加到上下文? 提前致谢。

问题是您将 resolvers 对象作为 rootValue 传递。相反,您应该将它们放在您的架构中,例如使用 makeExecutableSchema.

解析器有四个参数:父对象、字段参数、上下文和解析信息。

如果模式中的某个字段没有解析器,GraphQL 会退回到简单地使用父对象上的字段名访问 属性(即 rootValue 上的字段root Query 类型)。如果 属性 是一个方法,它会使用三个参数调用该方法(即 this = 父对象):字段参数、上下文和解析信息。