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?
GraphQL services typically respond using JSON, however the GraphQL spec does not require it. JSON may seem like an odd choice for an API layer promising better network performance, however because it is mostly text, it compresses exceptionally well with GZIP.
To use the explorer, we'll head to studio.apollographql.com/dev and create an account (using either GitHub or your email). Finally, choose a name for your graph, select the “Development” graph type, add your localhost endpoint (Apollo Server's default is http://localhost:4000), and click “Create Graph”. And that's it!
The GraphQL schema language supports the scalar types of String , Int , Float , Boolean , and ID , so you can use these directly in the schema you pass to buildSchema . By default, every type is nullable - it's legitimate to return null as any of the scalar types.
How To Get The Schema — Introspection Queries. Some GraphQL servers don't provide a convenient GraphQL API explorer. Instead, to get the schema we need to send a HTTP request to the GraphQL server endpoint asking for the GraphQL schema. This type of HTTP request is called a GraphQL introspection query.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With