33

我有一个突变

mutation deleteRecord($id: ID) {
    deleteRecord(id: $id) {
        id
    }
}

在另一个位置,我有一个元素列表。

有没有更好的东西可以从服务器返回,我应该如何更新列表?

更一般地说,在 apollo/graphql 中处理删除的最佳实践是什么?

4

6 回答 6

20

我不确定这是一种好的实践风格,但这是我使用 updateQueries 处理 react-apollo 中项目删除的方法:

import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import update from 'react-addons-update';
import _ from 'underscore';


const SceneCollectionsQuery = gql `
query SceneCollections {
  myScenes: selectedScenes (excludeOwner: false, first: 24) {
    edges {
      node {
        ...SceneCollectionScene
      }
    }
  }
}`;


const DeleteSceneMutation = gql `
mutation DeleteScene($sceneId: String!) {
  deleteScene(sceneId: $sceneId) {
    ok
    scene {
      id
      active
    }
  }
}`;

const SceneModifierWithStateAndData = compose(
  ...,
  graphql(DeleteSceneMutation, {
    props: ({ mutate }) => ({
      deleteScene: (sceneId) => mutate({
        variables: { sceneId },
        updateQueries: {
          SceneCollections: (prev, { mutationResult }) => {
            const myScenesList = prev.myScenes.edges.map((item) => item.node);
            const deleteIndex = _.findIndex(myScenesList, (item) => item.id === sceneId);
            if (deleteIndex < 0) {
              return prev;
            }
            return update(prev, {
              myScenes: {
                edges: {
                  $splice: [[deleteIndex, 1]]
                }
              }
            });
          }
        }
      })
    })
  })
)(SceneModifierWithState);
于 2016-11-21T20:47:49.573 回答
15

这是一个类似的解决方案,无需 underscore.js 即可工作。它react-apollo在 2.1.1 版本中进行了测试。并为删除按钮创建一个组件:

import React from "react";
import { Mutation } from "react-apollo";

const GET_TODOS = gql`
{
    allTodos {
        id
        name
    }
}
`;

const DELETE_TODO = gql`
  mutation deleteTodo(
    $id: ID!
  ) {
    deleteTodo(
      id: $id
    ) {
      id
    }
  }
`;

const DeleteTodo = ({id}) => {
  return (
    <Mutation
      mutation={DELETE_TODO}
      update={(cache, { data: { deleteTodo } }) => {
        const { allTodos } = cache.readQuery({ query: GET_TODOS });
        cache.writeQuery({
          query: GET_TODOS,
          data: { allTodos: allTodos.filter(e => e.id !== id)}
        });
      }}
      >
      {(deleteTodo, { data }) => (
        <button
          onClick={e => {
            deleteTodo({
              variables: {
                id
              }
            });
          }}
        >Delete</button>            
      )}
    </Mutation>
  );
};

export default DeleteTodo;
于 2018-04-03T20:20:08.853 回答
10

所有这些答案都假设面向查询的缓存管理。

如果我user使用 id删除1并且该用户在整个应用程序的 20 个查询中被引用怎么办?阅读上面的答案,我不得不假设我将不得不编写代码来更新所有这些的缓存。这对于代码库的长期可维护性来说是很糟糕的,并且会使任何重构都成为一场噩梦。

我认为最好的解决方案是这样apolloClient.removeItem({__typeName: "User", id: "1"})的:

  • 将缓存中对该对象的任何直接引用替换为null
  • [User]在任何查询中过滤掉任何列表中的此项

但它不存在(还)

这可能是个好主意,或者可能更糟(例如,它可能会破坏分页)

关于它有一个有趣的讨论:https ://github.com/apollographql/apollo-client/issues/899

我会小心那些手动查询更新。起初它看起来很诱人,但如果你的应用程序会增长,它就不会了。至少在其顶部创建一个可靠的抽象层,例如:

  • 在您定义的每个查询旁边(例如,在同一个文件中) - 定义正确对其进行清理的函数,例如

const MY_QUERY = gql``;

// it's local 'cleaner' - relatively easy to maintain as you can require proper cleaner updates during code review when query will change
export function removeUserFromMyQuery(apolloClient, userId) {
  // clean here
}

然后,收集所有这些更新并在最终更新中调用它们

function handleUserDeleted(userId, client) {
  removeUserFromMyQuery(userId, client)
  removeUserFromSearchQuery(userId, client)
  removeIdFrom20MoreQueries(userId, client)
}
于 2019-04-15T10:43:42.213 回答
9

对于 Apollo v3,这对我有用:

const [deleteExpressHelp] = useDeleteExpressHelpMutation({
  update: (cache, {data}) => {
    cache.evict({
      id: cache.identify({
        __typename: 'express_help',
        id: data?.delete_express_help_by_pk?.id,
      }),
    });
  },
});

从新文档

从缓存的数组字段中过滤悬空引用(如上面的 Deity.offspring 示例)非常普遍,以至于 Apollo 客户端会自动为未定义读取函数的数组字段执行此过滤。

于 2020-08-19T15:32:35.653 回答
4

就个人而言,我返回一个int代表已删除项目数的值。然后我使用updateQueries从缓存中删除文档。

于 2016-11-09T11:31:16.143 回答
1

当与突变相关的其余 API 可能返回 http 204、404 或 500 时,我在为此类突变选择适当的返回类型时遇到了同样的问题。

定义任意类型然后返回 null(类型默认可以为空)似乎不正确,因为您不知道发生了什么,这意味着它是否成功。

返回一个布尔值解决了这个问题,你知道突变是否有效,但你缺少一些信息以防它不起作用,比如你可以在 FE 上显示的更好的错误消息,例如,如果我们得到一个 404可以返回“未找到”。

返回自定义类型有点强迫,因为它实际上不是您的架构或业务逻辑的类型,它只是用于解决 rest 和 Graphql 之间的“通信问题”。

我最终返回了一个字符串。如果成功,我可以返回资源 ID/UUID 或简单地“确定”,并在出现错误时返回错误消息。

不确定这是否是一种好的做法或 Graphql 惯用语。

于 2019-11-17T17:45:21.397 回答