Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

fix: add optimistic updates for comments api in documents with many cards (#75763)

Uladzimir Havenchyk3e1f4bd247cd
diff --git a/frontend/src/metabase/api/comment.ts b/frontend/src/metabase/api/comment.ts
index 8a28207d685..5010706ce27 100644
--- a/frontend/src/metabase/api/comment.ts
+++ b/frontend/src/metabase/api/comment.ts
@@ -7,6 +7,7 @@ import {
provideUserListTags,
} from "metabase/api/tags";
import type {
+ BaseUser,
Comment,
CommentId,
CreateCommentRequest,
@@ -17,6 +18,15 @@ import type {
UpdateCommentRequest,
} from "metabase-types/api";
+export type DeleteCommentRequest = { id: CommentId } & ListCommentsRequest;
+
+export type ToggleReactionRequest = CreateReactionRequest &
+ ListCommentsRequest & {
+ currentUser: Pick<BaseUser, "id" | "common_name">;
+ };
+
+// Update the cached comments manually, because RTK won't refetch it while
+// another query is still running
export const commentApi = Api.injectEndpoints({
endpoints: (builder) => ({
listComments: builder.query<
@@ -40,6 +50,25 @@ export const commentApi = Api.injectEndpoints({
}),
invalidatesTags: (_, error) =>
invalidateTags(error, [listTag("comment")]),
+ async onQueryStarted(_request, { dispatch, queryFulfilled }) {
+ try {
+ const { data: comment } = await queryFulfilled;
+ dispatch(
+ commentApi.util.updateQueryData(
+ "listComments",
+ {
+ target_type: comment.target_type,
+ target_id: comment.target_id,
+ },
+ (draft) => {
+ draft.comments.push(comment);
+ },
+ ),
+ );
+ } catch {
+ // the caller reports the error; there is nothing to patch
+ }
+ },
}),
updateComment: builder.mutation<Comment, UpdateCommentRequest>({
@@ -50,20 +79,72 @@ export const commentApi = Api.injectEndpoints({
}),
invalidatesTags: (_, error, { id }) =>
invalidateTags(error, [idTag("comment", id), listTag("comment")]),
+ async onQueryStarted(_request, { dispatch, queryFulfilled }) {
+ try {
+ const { data: comment } = await queryFulfilled;
+ dispatch(
+ commentApi.util.updateQueryData(
+ "listComments",
+ {
+ target_type: comment.target_type,
+ target_id: comment.target_id,
+ },
+ (draft) => {
+ const index = draft.comments.findIndex(
+ ({ id }) => id === comment.id,
+ );
+ if (index !== -1) {
+ draft.comments[index] = comment;
+ }
+ },
+ ),
+ );
+ } catch {
+ console.error("Failed to update cached comment:", _request);
+ }
+ },
}),
- deleteComment: builder.mutation<void, CommentId>({
- query: (id) => ({
+ deleteComment: builder.mutation<void, DeleteCommentRequest>({
+ query: ({ id }) => ({
method: "DELETE",
url: `/api/comment/${id}`,
}),
- invalidatesTags: (_, error, id) =>
+ invalidatesTags: (_, error, { id }) =>
invalidateTags(error, [idTag("comment", id), listTag("comment")]),
+ async onQueryStarted(
+ { id, target_type, target_id },
+ { dispatch, queryFulfilled },
+ ) {
+ try {
+ await queryFulfilled;
+ dispatch(
+ commentApi.util.updateQueryData(
+ "listComments",
+ { target_type, target_id },
+ (draft) => {
+ const comment = draft.comments.find(
+ (comment) => comment.id === id,
+ );
+ if (comment) {
+ comment.deleted_at = new Date().toISOString();
+ }
+ },
+ ),
+ );
+ } catch {
+ console.error("Failed to delete cached comment:", {
+ id,
+ target_type,
+ target_id,
+ });
+ }
+ },
}),
toggleReaction: builder.mutation<
{ reacted: boolean },
- CreateReactionRequest
+ ToggleReactionRequest
>({
query: ({ id, emoji }) => ({
method: "POST",
@@ -72,6 +153,73 @@ export const commentApi = Api.injectEndpoints({
}),
invalidatesTags: (_, error, { id }) =>
invalidateTags(error, [idTag("comment", id), listTag("comment")]),
+ async onQueryStarted(
+ { id, emoji, target_type, target_id, currentUser },
+ { dispatch, queryFulfilled },
+ ) {
+ // unlike the pessimistic patches above, reactions toggle optimistically
+ // (before the response) and roll back on error
+ const patch = dispatch(
+ commentApi.util.updateQueryData(
+ "listComments",
+ { target_type, target_id },
+ (draft) => {
+ const comment = draft.comments.find(
+ (comment) => comment.id === id,
+ );
+ if (!comment) {
+ return;
+ }
+
+ const reaction = comment.reactions.find(
+ (reaction) => reaction.emoji === emoji,
+ );
+ const hasReacted = reaction?.users.some(
+ (user) => user.id === currentUser.id,
+ );
+
+ if (reaction && hasReacted) {
+ reaction.users = reaction.users.filter(
+ (user) => user.id !== currentUser.id,
+ );
+ reaction.count -= 1;
+ if (reaction.count <= 0) {
+ comment.reactions = comment.reactions.filter(
+ ({ emoji }) => emoji !== reaction.emoji,
+ );
+ }
+ } else if (reaction) {
+ reaction.users.push({
+ id: currentUser.id,
+ name: currentUser.common_name,
+ });
+ reaction.count += 1;
+ } else {
+ comment.reactions.push({
+ emoji,
+ count: 1,
+ users: [
+ { id: currentUser.id, name: currentUser.common_name },
+ ],
+ });
+ }
+ },
+ ),
+ );
+
+ try {
+ await queryFulfilled;
+ } catch {
+ patch.undo();
+ console.error("Failed to toggle reaction on cached comment:", {
+ id,
+ emoji,
+ target_type,
+ target_id,
+ currentUser,
+ });
+ }
+ },
}),
listMentions: builder.query<
diff --git a/frontend/src/metabase/api/comment.unit.spec.ts b/frontend/src/metabase/api/comment.unit.spec.ts
new file mode 100644
index 00000000000..7adf17fd3b0
--- /dev/null
+++ b/frontend/src/metabase/api/comment.unit.spec.ts
@@ -0,0 +1,144 @@
+import { waitFor } from "@testing-library/react";
+import fetchMock from "fetch-mock";
+
+import { getStore } from "__support__/entities-store";
+import { setupCommentEndpoints } from "__support__/server-mocks";
+import type { Comment } from "metabase-types/api";
+import { createMockComment } from "metabase-types/api/mocks/comment";
+import { createMockDocumentContent } from "metabase-types/api/mocks/document";
+
+import { Api } from "./api";
+import { cardApi } from "./card";
+import { commentApi } from "./comment";
+
+const LIST_REQUEST = { target_type: "document" as const, target_id: 1 };
+const CURRENT_USER = { id: 7, common_name: "Current User" };
+
+let activeStore: ReturnType<typeof getStore> | undefined;
+
+async function setup({ comments }: { comments: Comment[] }) {
+ setupCommentEndpoints(comments, LIST_REQUEST);
+
+ const store = getStore({ [Api.reducerPath]: Api.reducer }, {}, [
+ Api.middleware,
+ ]);
+ activeStore = store;
+
+ const getCachedComments = () =>
+ commentApi.endpoints.listComments.select(LIST_REQUEST)(store.getState())
+ .data?.comments;
+
+ store.dispatch(commentApi.endpoints.listComments.initiate(LIST_REQUEST));
+ await waitFor(() =>
+ expect(getCachedComments()).toHaveLength(comments.length),
+ );
+
+ return { store, getCachedComments };
+}
+
+describe("commentApi cache updates", () => {
+ afterEach(() => {
+ // Abort in-flight queries before removing the fetch routes.
+ activeStore?.dispatch(Api.util.resetApiState());
+ activeStore = undefined;
+ fetchMock.removeRoutes().clearHistory();
+ });
+
+ it("shows a created comment even while invalidation is starved by an in-flight query", async () => {
+ const { store, getCachedComments } = await setup({
+ comments: [createMockComment({ id: 1, ...LIST_REQUEST })],
+ });
+ const newComment = createMockComment({ id: 2, ...LIST_REQUEST });
+ fetchMock.post("path:/api/comment", newComment);
+
+ // simulate never-resolving query
+ fetchMock.get("path:/api/card/1", new Promise(() => {}));
+ store.dispatch(cardApi.endpoints.getCard.initiate({ id: 1 }));
+
+ await store.dispatch(
+ commentApi.endpoints.createComment.initiate({
+ ...LIST_REQUEST,
+ child_target_id: "node-1",
+ parent_comment_id: null,
+ content: createMockDocumentContent(),
+ }),
+ );
+
+ expect(getCachedComments()?.map(({ id }) => id)).toEqual([1, 2]);
+ expect(
+ fetchMock.callHistory.calls("path:/api/comment", { method: "GET" }),
+ ).toHaveLength(1);
+ });
+
+ it("patches the cached comment when it is updated", async () => {
+ const comment = createMockComment({ id: 1, ...LIST_REQUEST });
+ const { store, getCachedComments } = await setup({ comments: [comment] });
+ fetchMock.put("path:/api/comment/1", { ...comment, is_resolved: true });
+
+ await store.dispatch(
+ commentApi.endpoints.updateComment.initiate({ id: 1, is_resolved: true }),
+ );
+
+ expect(getCachedComments()?.[0]?.is_resolved).toBe(true);
+ });
+
+ it("marks the cached comment as deleted when it is deleted", async () => {
+ const { store, getCachedComments } = await setup({
+ comments: [createMockComment({ id: 1, ...LIST_REQUEST })],
+ });
+ fetchMock.delete("path:/api/comment/1", 204);
+
+ await store.dispatch(
+ commentApi.endpoints.deleteComment.initiate({ id: 1, ...LIST_REQUEST }),
+ );
+
+ expect(getCachedComments()?.[0]?.deleted_at).toEqual(expect.any(String));
+ });
+
+ it("toggles the current user's reaction on the cached comment", async () => {
+ const { store, getCachedComments } = await setup({
+ comments: [createMockComment({ id: 1, ...LIST_REQUEST, reactions: [] })],
+ });
+ fetchMock.post("path:/api/comment/1/reaction", { reacted: true });
+
+ const toggle = () =>
+ store.dispatch(
+ commentApi.endpoints.toggleReaction.initiate({
+ id: 1,
+ emoji: "🤣",
+ ...LIST_REQUEST,
+ currentUser: CURRENT_USER,
+ }),
+ );
+
+ await toggle();
+ expect(getCachedComments()?.[0]?.reactions).toEqual([
+ {
+ emoji: "🤣",
+ count: 1,
+ users: [{ id: CURRENT_USER.id, name: CURRENT_USER.common_name }],
+ },
+ ]);
+
+ await toggle();
+ expect(getCachedComments()?.[0]?.reactions).toEqual([]);
+ });
+
+ it("reverts the reaction patch when the request fails", async () => {
+ const { store, getCachedComments } = await setup({
+ comments: [createMockComment({ id: 1, ...LIST_REQUEST, reactions: [] })],
+ });
+ fetchMock.post("path:/api/comment/1/reaction", 500);
+
+ await store.dispatch(
+ commentApi.endpoints.toggleReaction.initiate({
+ id: 1,
+ emoji: "🤣",
+ ...LIST_REQUEST,
+ currentUser: CURRENT_USER,
+ }),
+ );
+
+ expect(getCachedComments()?.[0]?.reactions).toEqual([]);
+ });
+});
diff --git a/frontend/src/metabase/comments/components/Discussion/Discussion.tsx b/frontend/src/metabase/comments/components/Discussion/Discussion.tsx
index 3dadf0ba086..5411a77d889 100644
--- a/frontend/src/metabase/comments/components/Discussion/Discussion.tsx
+++ b/frontend/src/metabase/comments/components/Discussion/Discussion.tsx
@@ -71,7 +71,11 @@ export const Discussion = ({
};
const handleDeleteComment = async (comment: Comment) => {
- const { error } = await deleteComment(comment.id);
+ const { error } = await deleteComment({
+ id: comment.id,
+ target_type: comment.target_type,
+ target_id: comment.target_id,
+ });
if (error) {
sendToast({
@@ -142,30 +146,38 @@ export const Discussion = ({
sendToast({ icon: "check", message: t`Copied link` });
};
- const handleReaction = async (comment: Comment, emoji: string) => {
- const { error } = await toggleReaction({ id: comment.id, emoji });
-
- if (error) {
- sendToast({
- icon: "warning_triangle_filled",
- iconColor: "warning",
- message: t`Failed to add reaction`,
- });
+ const handleToggleReaction = async (
+ comment: Comment,
+ emoji: string,
+ errorMessage: string,
+ ) => {
+ if (!currentUser) {
+ return;
}
- };
- const handleReactionRemove = async (comment: Comment, emoji: string) => {
- const { error } = await toggleReaction({ id: comment.id, emoji });
+ const { error } = await toggleReaction({
+ id: comment.id,
+ emoji,
+ target_type: comment.target_type,
+ target_id: comment.target_id,
+ currentUser,
+ });
if (error) {
sendToast({
icon: "warning_triangle_filled",
iconColor: "warning",
- message: t`Failed to remove reaction`,
+ message: errorMessage,
});
}
};
+ const handleReaction = (comment: Comment, emoji: string) =>
+ handleToggleReaction(comment, emoji, t`Failed to add reaction`);
+
+ const handleReactionRemove = (comment: Comment, emoji: string) =>
+ handleToggleReaction(comment, emoji, t`Failed to remove reaction`);
+
const handleMouseEnter = () => {
if (enableHoverHighlight && effectiveChildTargetId) {
dispatch(setHoveredChildTargetId(String(effectiveChildTargetId)));