哪种GraphQL类型用于从查询返回非结构化数据?

时间:2018-11-02 23:47:33

标签: javascript mongoose graphql relay relaymodern

我正在构建一个动态查询报告,该报告将向服务器发送查询并获取行列表。我正在使用relayMongoose。对于每个查询,我都会根据报告配置获得不同的列和格式。

我的GraphQLQuery看起来像:

const reportExec = {
    type: new GraphQLList(ReportRowType), <=== What type should be returned ?
    description: "Execute a dynamic query",
    args: {
        id: {
            name: "id",
            type: new GraphQLNonNull(GraphQLID)
        }
    },
    resolve(source, args, context) {
        return processQuery(context, args.id)
    }
};

我的过程功能:

let fields = ... // Query fields from dynamic logic
let filters = ... // Query filters from dynamic logic
let reportModel = ... // Dynamically selects the correct collection to get data from


return reportModel.find(query, fields).limit(10000).exec();

因此,最后我得到了行列表:

{ _id: "...", field1: ..., field2: ... }
{ _id: "...", field1: ..., field2: ... }
{ _id: "...", field1: ..., field2: ... }

我建立了以下类型:

export const ReportRowType = new GraphQLObjectType({
    name: "ReportRow",
    description: "ReportRow",
    fields: () => ({
        data: {
            type: new GraphQLList(GraphQLMixed)
        }
    })
});

但是我每行只得到null

如何正确设置返回类型以从查询中获取非结构化数据(具有可变列数的行列表以及在不同运行中具有不同类型的每一列)?

1 个答案:

答案 0 :(得分:0)

最简单的解决方案可能是利用JSON标量,例如graphql-type-json。尽管您可以将其包含在类型验证中,但您甚至不一定需要使用GraphQLList包装器。

import GraphQLJSON from 'graphql-type-json';

const reportExec = {
    type: GraphQLJSON,
    description: "Execute a dynamic query",
    args: {
        id: {
            name: "id",
            type: new GraphQLNonNull(GraphQLID)
        }
    },
    resolve(source, args, context) {
        return processQuery(context, args.id)
    }
};