[英]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(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: [],
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
object 作為rootValue
。 相反,您應該將它們放入您的架構中,例如使用makeExecutableSchema
。
解析器需要四個 arguments:父 object、字段 arguments、上下文和解析信息。
如果架構中的字段沒有解析器,則 GraphQL 會退回到簡單地使用父 object 上的字段名稱訪問屬性(這是根Query
類型上字段的rootValue
)。 如果該屬性是一個方法,它會使用三個 arguments 調用該方法(即this
= 父對象):字段 arguments、上下文和解析信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.