如何在Graphql中返回JSON对象并定义JSON类型

时间:2019-08-07 18:05:11

标签: javascript node.js graphql

我想在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;
            }
        },

1 个答案:

答案 0 :(得分:0)

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

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

或使用解构语法:

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