How to use graphql-type-json package with GraphQl

2020-04-06 16:10发布

I can't get GraphQL to recognize the JSON scalar type.

I followed the [apollo docs] (http://dev.apollodata.com/tools/graphql-tools/scalars.html#Using-a-package) to define a JSON GraphQL scalar type for my schema:

Schema:

const SchemaDefinition = `
   scalar JSON
   schema {
     query: Query
     mutation: Mutation
  }
`

export default [
  SchemaDefinition,
  Query,
  Mutation,
  ...
]

Test type:

const Test = `
  type Test {
    bodyJson: JSON
 }`

Resolver:

import GraphQLJSON from 'graphql-type-json'

const QueryResolver = {
  Query: {
    viewer(root, args, ctx) {
      return User.query()
        .where('id', ctx.state.user)
        .first()
     }
  }
}

const scalarJSON = {
  JSON: GraphQLJSON
}

export default {
  ...QueryResolver,
  ...ViewerResolver,
  ...scalarJSON
  ...
}

I'm using PostgreSQL and the column I'm querying (body_json) is of data type jsonb.

If I test my schema through GraphiQL, when I return the value straight from the db (I use Knex to query) I get this error message from GraphQL:

Expected a value of type \"JSON\" but received: [object Object]

If I use JSON.stringify first on the returned value, I get this error:

"Expected a value of type \"JSON\" but received: {\"key\":\"test\"}"

Any suggestion as to what I might be doing wrong?

2条回答
Emotional °昔
2楼-- · 2020-04-06 16:34

I resolved custom scalar JSON like this in resolvers

 JSON: {

__serialize(value) {
    return GraphQLJSON.parseValue(value);
} }

And It worked fine for me. I think it will help you

查看更多
【Aperson】
3楼-- · 2020-04-06 16:35

I couldn't get a custom scalar working with a text-based schema (using buildSchema('...') from the core "graphql" library), but it worked when I built the schema programmatically from scratch (using new GraphQLSchema(...)).

查看更多
登录 后发表回答