如何在 GraphQl 中使用 graphql-type-json 包 [英] How to use graphql-type-json package with GraphQl
问题描述
我无法让 GraphQL 识别 JSON 标量类型.
I can't get GraphQL to recognize the JSON scalar type.
我遵循了 [apollo docs] (http://dev.apollodata.com/tools/graphql-tools/scalars.html#Using-a-package) 为我的模式定义一个 JSON GraphQL 标量类型:
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:
架构:
const SchemaDefinition = `
scalar JSON
schema {
query: Query
mutation: Mutation
}
`
export default [
SchemaDefinition,
Query,
Mutation,
...
]
测试类型:
const Test = `
type Test {
bodyJson: JSON
}`
解析器:
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
...
}
我使用的是 PostgreSQL,我查询的列 (body_json) 的数据类型为 jsonb.
I'm using PostgreSQL and the column I'm querying (body_json) is of data type jsonb.
如果我通过 GraphiQL 测试我的架构,当我直接从数据库返回值(我使用 Knex 进行查询)时,我会从 GraphQL 收到此错误消息:
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:
应为 "JSON" 类型的值,但收到:[object Object]
Expected a value of type "JSON" but received: [object Object]
如果我首先在返回值上使用 JSON.stringify,我会收到这个错误:
If I use JSON.stringify first on the returned value, I get this error:
"期望类型为 "JSON" 的值但收到:{"key":"test"}"
"Expected a value of type "JSON" but received: {"key":"test"}"
对我可能做错了什么有什么建议吗?
Any suggestion as to what I might be doing wrong?
推荐答案
我在解析器中像这样解析了自定义标量 JSON
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
这篇关于如何在 GraphQl 中使用 graphql-type-json 包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!