如何在GraphQl中使用graphql-type-json包 [英] How to use graphql-type-json package with GraphQl

查看:442
本文介绍了如何在GraphQl中使用graphql-type-json包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让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-包)来为我的模式定义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,而我正在使用的列m查询(body_json)的数据类型为jsonb。

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

如果我通过GraphiQL测试架构,则直接从db返回值(我使用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 type的值,但收到:[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆