我有一个我的 GraphQL 客户端请求的对象。
这是一个相当简单的对象:
type Element {
content: [ElementContent]
elementId: String
name: String
notes: String
type: String
createdAt: String
updatedAt: String
}
使用特殊类型 ElementContent
,它很小,看起来像这样:
type ElementContent {
content: String
locale: String
}
现在,当我在客户端查询这个时,顶级对象和低级对象都有额外的属性(如果我试图按原样克隆主体,这会干扰更新对象);
值得注意的是,GraphQL 似乎在父对象中提供了一个 __typename
属性,在子对象中,它们也有 typename 和一个 Symbol(id)
属性。
我想将此对象复制到状态,更新状态,然后克隆状态并将其发送到我的 update
突变。但是,由于 GraphQL 本身提供的未知属性,我遇到了障碍。
我试过:
delete element.__typename
效果很好,但我还需要遍历子项(对象的动态数组),并且可能还必须删除这些属性。
我不确定在这个等式中我是否遗漏了什么,或者我应该努力完成代码并循环 + 删除(我最初尝试执行 forEach 循环时收到错误消息)。对于我正在尝试做的事情,有更好的策略吗?还是我在正确的道路上,只需要一些好的循环代码来清除不需要的属性?
最佳答案
三种方式
第一种方式
像这样更新客户端参数,它将忽略 graphql 中不需要的字段。
apollo.create({
link: http,
cache: new InMemoryCache({
addTypename: false
})
});
第二种方式
通过使用 omit-deep打包并作为中间件使用
const cleanTypeName = new ApolloLink((operation, forward) => {
if (operation.variables) {
operation.variables = omitDeep(operation.variables,'__typename')
}
return forward(operation).map((data) => {
return data;
});
});
第三条路
创建自定义中间件并注入(inject) apollo
const cleanTypeName = new ApolloLink((operation, forward) => {
if (operation.variables) {
const omitTypename = (key, value) => (key === '__typename' ? undefined : value);
operation.variables = JSON.parse(JSON.stringify(operation.variables), omitTypename);
}
return forward(operation).map((data) => {
return data;
});
});
并注入(inject)中间件
const httpLinkWithErrorHandling = ApolloLink.from([
cleanTypeName,
retry,
error,
http,
]);
如果您将片段与查询/突变一起使用,建议使用 Second Way 和 Third Way。
首选方法是Third Way,因为它没有任何第三方依赖,也没有缓存性能问题
关于javascript - 从 GraphQL 响应中清除不需要的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47211778/