6

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 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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(...)).

1 Comment

Ok, I'll look into that. Thank you. I'll update here if I get anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.