Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add useRunTransactionMutation #110

Merged
merged 2 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/react/src/firestore/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// useEnableIndexedDbPersistenceMutation
// useDisableNetworkMutation
// useEnableNetworkMutation
// useRunTransactionMutation
export { useRunTransactionMutation } from "./useRunTransactionMutation";
// useWaitForPendingWritesQuery
// useWriteBatchCommitMutation (WriteBatch)
export { useDocumentQuery } from "./useDocumentQuery";
Expand Down
138 changes: 138 additions & 0 deletions packages/react/src/firestore/useRunTransactionMutation.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import React from "react";
import { describe, expect, test, beforeEach, vi } from "vitest";
import { renderHook, act, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { firestore, wipeFirestore } from "~/testing-utils";
import { useRunTransactionMutation } from "./useRunTransactionMutation";
import { doc, getDoc, setDoc, type Transaction } from "firebase/firestore";

const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});

const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);

describe("useRunTransactionMutation", () => {
beforeEach(async () => {
queryClient.clear();
await wipeFirestore();
});

test("should successfully perform a transaction and update a Firestore document", async () => {
const docRef = doc(firestore, "tests", "transactionDoc");
await setDoc(docRef, { foo: "bar" });

const updateFunction = async (transaction: Transaction) => {
transaction.set(docRef, { foo: "updatedDoc" });
};

const { result } = renderHook(
() => useRunTransactionMutation(firestore, updateFunction),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => expect(result.current.isSuccess).toBe(true));

// Verify the document was actually updated
const docSnapshot = await getDoc(docRef);
expect(docSnapshot.exists()).toBe(true);
expect(docSnapshot.data()).toEqual({ foo: "updatedDoc" });
});

test("should perform a transaction with options and update a Firestore document", async () => {
const docRef = doc(firestore, "tests", "transactionDoc");

await setDoc(docRef, { foo: "bar" });

const updateFunction = async (transaction: Transaction) => {
transaction.set(docRef, { foo: "updatedWithOptions" });
};

const { result } = renderHook(
() =>
useRunTransactionMutation(firestore, updateFunction, {
firestore: { maxAttempts: 1 },
}),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => expect(result.current.isSuccess).toBe(true));

const docSnapshot = await getDoc(docRef);
expect(docSnapshot.exists()).toBe(true);

Check failure on line 71 in packages/react/src/firestore/useRunTransactionMutation.test.tsx

View workflow job for this annotation

GitHub Actions / test

packages/react/src/firestore/useRunTransactionMutation.test.tsx > useRunTransactionMutation > should perform a transaction with options and update a Firestore document

AssertionError: expected false to be true // Object.is equality - Expected + Received - true + false ❯ packages/react/src/firestore/useRunTransactionMutation.test.tsx:71:34
expect(docSnapshot.data()).toEqual({ foo: "updatedWithOptions" });
});

test("should handle transaction errors correctly", async () => {
const updateFunction = async () => {
throw new Error("Transaction failed");
};

const { result } = renderHook(
() => useRunTransactionMutation(firestore, updateFunction),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => expect(result.current.isError).toBe(true));

expect(result.current.isError).toBe(true);
expect(result.current.error?.message).toBe("Transaction failed");
});

test("should call onSuccess callback when transaction is successful", async () => {
const updateFunction = async (transaction: Transaction) => {
const docRef = doc(firestore, "tests", "transactionDoc");
transaction.set(docRef, { foo: "onSuccessTest" });
return "Success";
};

const onSuccessMock = vi.fn();

const { result } = renderHook(
() =>
useRunTransactionMutation(firestore, updateFunction, {
onSuccess: onSuccessMock,
}),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => expect(result.current.isSuccess).toBe(true));

expect(onSuccessMock).toHaveBeenCalled();
});

test("should call onError callback when transaction fails", async () => {
const updateFunction = async () => {
throw new Error("Transaction failed");
};

const onErrorMock = vi.fn();

const { result } = renderHook(
() =>
useRunTransactionMutation(firestore, updateFunction, {
onError: onErrorMock,
}),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => expect(result.current.isError).toBe(true));

expect(onErrorMock).toHaveBeenCalled();
});
});
31 changes: 31 additions & 0 deletions packages/react/src/firestore/useRunTransactionMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { useMutation, type UseMutationOptions } from "@tanstack/react-query";
import {
Firestore,
FirestoreError,
Transaction,
runTransaction,
TransactionOptions,
} from "firebase/firestore";

type RunTransactionFunction<T> = (transaction: Transaction) => Promise<T>;

type FirestoreUseMutationOptions<TData = unknown, TError = Error> = Omit<
UseMutationOptions<TData, TError, void>,
"mutationFn"
> & {
firestore?: TransactionOptions;
};

export function useRunTransactionMutation<T>(
firestore: Firestore,
updateFunction: RunTransactionFunction<T>,
options?: FirestoreUseMutationOptions<T>
) {
const { firestore: firestoreOptions, ...queryOptions } = options ?? {};

return useMutation<T, FirestoreError, void>({
...queryOptions,
mutationFn: () =>
runTransaction(firestore, updateFunction, firestoreOptions),
});
}
Loading