问题描述
我正在使用 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(context) 说的:
{
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: [],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
上字段的 Query
类型)。如果该属性是一个方法,它会使用三个参数调用该方法(即 this
= 父对象):字段参数、上下文和解析信息。