在 Angular 中动态创建 Apollo GraphQL 突变调用

Dynamically creating Apollo GraphQL mutation call in Angular

我的 Angular 应用程序中有一个有效的突变调用,用于使用 Apollo GraphQL 突变对象的某些字段。突变调用的一部分包括一些 return 数据,Apollo 将这些数据与其缓存中已有的某个对象相关联,并使用新值更新它 returned.

我只想 return 个实际被改变的字段,以避免通过网络发送大数据包。

我已经成功地动态生成了一个只包含被突变字段的突变文档,我将其传递给 apollo.mutate({mutation: newMutation, ...}),其中 return 是一个可观察对象。只有订阅了可观察对象,才会触发突变。我已经验证使用该订阅的组件正在取消订阅并在调用新突变之前被销毁。

问题是 Apollo 正在缓存变异文档并为所有调用发送第一个变异(只有第一次变异的字段)。我已通过检查网络浏览器的网络选项卡验证了这一点。

我已经尝试让 Apollo 停止缓存它,方法是通过附加日期时间来使用唯一的突变名称。我检查过突变的变量是唯一的。我试过使用片段,但片段也需要动态生成,这是同样的问题。

有人知道我做错了什么吗?

好的,我明白了。 Apollo Client 正在向其 ROOT_MUTATION 添加变更文档。我发现使用 Apollo Client 的 writeData/writeQuery 函数只能让你 add/modify ROOT_QUERY.

最初我试图将字段动态添加到我的 GraphQL AST。代码看起来像这样:

import gql from 'graphql-tag';
...
const myMutation = gql`
  mutation myMutation($id: ID!, ...) {
    mutateFields(id: $id, ...) {
      id  # You need to return at least one field or it will complain
      # Add mutated fields to return here
    }
  }
`;

# dynamically call the following lines based on fields to be added
myMutation.definitions[0].selectionSet.selections[0].selectionSet.selections = [
  {...}  # Added my own fields and their subfields here
];

问题是它第一次工作,所以我知道我正确地修改了 GraphQL AST,但后续调用(使用 return 的新字段)被正确创建但 Apollo 发出了第一个同名突变(我检查了浏览器的网络选项卡以进行验证)。

解决方案:

不要修改 GraphQL AST,而是将其修改为字符串文字,类似于 Alireza Hariri 对此 post 的评论:GraphQL dynamic query building.

示例代码:

const mainMutation = `
   mutation myMutation($id: ID!, ...) {
    mutateFields(id: $id, ...) {
      id  # You need to return at least one field or it will complain
      # REPLACE_THIS_WITH_FIELDS
    }
  }
`;

const mutationWithFields = mainMutation.replace(
  `# REPLACE_THIS_WITH_FIELDS`,
  "myField { mySubfield1 mySubfield2 }"
);

const finalMutation = gql`${mutationWithFields}`;
this.apollo.mutate({
  mutation: finalMutation,
  variables: {
    id: myId,
    ...
  }
});