【问题标题】:How can I return a JSON object in Graphql and define JSON type如何在 Graphql 中返回 JSON 对象并定义 JSON 类型
【发布时间】:2019-12-15 10:09:41
【问题描述】:

我想在 graphiql 界面的 metas 字段中将我的结果作为 JSON OBJECT 返回,如果无法定义 JSON OBJECT,我如何为 JSON OBJECT 定义自定义标量。

我已经尝试将 graphql-type-json 中的 GraphQLJSON 作为 npm 包,但是当我使用它时,它会抛出一条错误消息,指出字段类型必须是输出类型

const PostType = new GraphQLObjectType({
    name : "Post",
    fields : () => ({
        id : { type:  GraphQLInt }, 
        title : { type:  GraphQLString },
        slug : { type:  GraphQLString },
        content : { type:  GraphQLString },
        type : { type:  GraphQLString },
        template : { type:  GraphQLString },
        link : { type:  GraphQLString },
        doctor_id : { type:  GraphQLInt },
        categories : { type:  GraphQLString },
        publishdate: {type: GraphQLDate},
        metas: {type:  GraphQLJSON  }

    })
})

const mutation = new GraphQLObjectType({
    name: 'Mutation',
    fields: {
        /********* Post */
        createPost: {
            type: schemaObjects.PostType,
            args: {
                title: { type: GraphQLString },
                slug: { type: GraphQLString },
                content: { type: GraphQLString },
                type: { type: GraphQLString },
                status: { type: GraphQLString },
                template: { type: GraphQLString },
                categories: { type: GraphQLString },
                doctor_id: { type: GraphQLInt },
                link: { type: GraphQLString },
                publishdate: { type: GraphQLDate},
                metas: {type:GraphQLJSON }
                ,
            resolve(parentValue, args) {
                let post = PostController.create(args);

                return post;
            }
        },

【问题讨论】:

  • 你是如何导入GraphQLJSON的?
  • 感谢丹尼尔与我们联系。我正在使用 const GraphQLJSON = require('graphql-type-json');但我已经尝试使用 import GraphQLJSON from 'graphql-type-json' ,但效果不佳。
  • 试试const { GraphQLJSON } = require('graphql-type-json')
  • @DanielRearden 非常感谢!这对我有用。

标签: javascript node.js graphql


【解决方案1】:

graphql-type-json 模块导出一个对象,其中包含库添加的两种类型。假设您使用的是普通的旧 Node.js,您可以像这样导入类型:

const GraphQLJSON = require('graphql-type-json').GraphQLJSON

或使用解构语法:

const { GraphQLJSON } = require('graphql-type-json')

【讨论】:

  • 谢谢!帮了我很多。很高兴在这个社区中看到像您这样的人。
猜你喜欢
  • 2018-10-19
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多