突变中的单个JSON参数

时间:2016-08-09 23:36:16

标签: json graphql graphql-js

下面我试图用一个object-arg example设置一个变异credentials。之前我有这个工作然后突然它停止工作失败的JSON部分。为什么我不能通过credentials发送json?

import {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLInt,
  GraphQLInputObjectType,
  GraphQLNonNull,
  graphql
} from 'graphql'


let requestType = new GraphQLInputObjectType({
  name: 'Request',
  fields: {
    name: {type: GraphQLString},
  }
})

let responseType = new GraphQLObjectType({
  name: 'Response',
  fields: {
    name: {type: GraphQLString},
    age: {type: GraphQLInt}
  }
})

let schema = new GraphQLSchema({
  query:  new GraphQLObjectType({
    name: 'Query',
    fields: {
      author: {
        type: GraphQLString,
        resolve: (source, args, context, info) => {
          return 'Thomas Reggi'
        }
      }
    }
  }),
  mutation: new GraphQLObjectType({
    name: 'Mutation',
    fields: {
      example: {
        type: responseType,
        args: {
          credentials: {
            name: 'credentials',
            type: requestType
          }
        },
        resolve: (source, args, context, info) => {
          return {
            'name': 'Thomas Reggi',
            'age': 26
          }
        }
      }
    }
  })
})

let credentials = { name: "Thomas Reggi" }

let requestString = `
mutation {
  example(credentials: ${JSON.stringify(credentials)}) {
    name,
    age
  }
}`

graphql(schema, requestString).then(result => {
  console.log(result)
})

这是错误:

{ errors: 
   [ Syntax Error GraphQL request (3:25) Expected Name, found String "name: "

     2: mutation {
     3:   example(credentials: {"name":"Thomas Reggi"}) {
                                ^
     4:     name,
      ] }

Name的引用来自何处?为什么会抛出错误?

1 个答案:

答案 0 :(得分:4)

刚刚找到了困难的方法。您无法{"name": "Thomas Reggi"}因为名称在引号中。

此查询有效。

mutation {
  example(credentials: {name: "Thomas Reggi"}) {
    name,
    age
  }
}