【发布时间】:2018-02-01 05:03:02
【问题描述】:
我们的 GraphQL 查询的响应必须返回对象的一些动态属性。在我们的例子中,我们无法预定义所有可能的属性 - 所以它必须是动态的。
我们认为有两种解决方案。
const MyType = new GraphQLObjectType({
name: 'SomeType',
fields: {
name: {
type: GraphQLString,
},
elements: {
/*
THIS is our special field which needs to return a dynamic object
*/
},
// ...
},
});
正如您在示例代码中看到的,元素是必须返回对象的属性。解决此问题时的响应可能是:
{
name: 'some name',
elements: {
an_unkonwn_key: {
some_nested_field: {
some_other: true,
},
},
another_unknown_prop: 'foo',
},
}
1) 返回“任意对象”
我们可以只返回任何对象——所以 GraphQL 不需要知道对象有哪些字段。当我们告诉 GraphQL 该字段是 GraphQlObjectType 类型时,它需要定义字段。因此,似乎不可能告诉 GraphQL 某人只是一个对象。
为此,我们已将其更改为:
elements: {
type: new GraphQLObjectType({ name: 'elements' });
},
2) 我们可以定义动态字段属性,因为它在函数中
当我们将字段定义为一个函数时,我们可以动态地定义我们的对象。但是字段函数需要一些信息(在我们的例子中是传递给元素的信息),我们需要访问它们来构建字段对象。
例子:
const MyType = new GraphQLObjectType({
name: 'SomeType',
fields: {
name: {
type: GraphQLString,
},
elements: {
type: new GraphQLObjectType({
name: 'elements',
fields: (argsFromElements) => {
// here we can now access keys from "args"
const fields = {};
argsFromElements.keys.forEach((key) => {
// some logic here ..
fields[someGeneratedProperty] = someGeneratedGraphQLType;
});
return fields;
},
}),
args: {
keys: {
type: new GraphQLList(GraphQLString),
},
},
},
// ...
},
});
这可行,但问题是是否有办法将参数和/或解析对象传递给字段。
问题 所以我们现在的问题是:在我们的 GraphQL 案例中推荐哪种方式,解决方案 1 或 2 可能吗?也许还有其他解决方案?
编辑 解决方案 1 在使用 ScalarType 时会起作用。示例:
type: new GraphQLScalarType({
name: 'elements',
serialize(value) {
return value;
},
}),
我不确定这是否是解决我们问题的推荐方法。
【问题讨论】:
标签: javascript graphql