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 useNamedQuery hook #107

Draft
wants to merge 4 commits into
base: next
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -9,4 +9,4 @@ export { useDocumentQuery } from "./useDocumentQuery";
// useDocumentsQuery <-- Name? useQuery? Bit generic.
// useGetCountFromServerQuery
// useGetAggregateFromServerQuery
// useNamedQuery
export { useNamedQuery } from "./useNamedQuery";
164 changes: 164 additions & 0 deletions packages/react/src/firestore/useNamedQuery.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import React, { type ReactNode } from "react";
import { describe, expect, test, beforeEach } from "vitest";
import { useNamedQuery } from "./useNamedQuery";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
collection,
addDoc,
query,
where,
DocumentData,
QuerySnapshot,
} from "firebase/firestore";

import {
expectFirestoreError,
firestore,
wipeFirestore,
} from "~/testing-utils";

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

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

describe("useNamedQuery", () => {
beforeEach(async () => await wipeFirestore());

test("returns correct data for empty collection", async () => {
const collectionRef = collection(firestore, "tests");

const { result } = renderHook(
() =>
useNamedQuery(collectionRef, {
queryKey: ["named", "empty"],
}),
{ wrapper }
);

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

expect(result.current.data?.empty).toBe(true);
expect(result.current.data?.docs.length).toBe(0);
});

test("returns correct data for non-empty collection", async () => {
const collectionRef = collection(firestore, "tests");

await addDoc(collectionRef, { value: 10 });
await addDoc(collectionRef, { value: 20 });

const { result } = renderHook(
() =>
useNamedQuery(collectionRef, {
queryKey: ["named", "non-empty"],
}),
{ wrapper }
);

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

expect(result.current.data?.empty).toBe(false);
expect(result.current.data?.docs.length).toBe(2);
});

test("handles complex queries", async () => {
const collectionRef = collection(firestore, "tests");

await addDoc(collectionRef, { category: "A", value: 10 });
await addDoc(collectionRef, { category: "B", value: 20 });
await addDoc(collectionRef, { category: "A", value: 30 });

const complexQuery = query(collectionRef, where("category", "==", "A"));

const { result } = renderHook(
() =>
useNamedQuery(complexQuery, {
queryKey: ["named", "complex"],
}),
{ wrapper }
);

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

expect(result.current.data?.empty).toBe(false);
expect(result.current.data?.docs.length).toBe(2);
});

test("handles restricted collections appropriately", async () => {
const restrictedCollectionRef = collection(
firestore,
"restrictedCollection"
);

const { result } = renderHook(
() =>
useNamedQuery(restrictedCollectionRef, {
queryKey: ["named", "restricted"],
}),
{ wrapper }
);

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

expectFirestoreError(result.current.error, "permission-denied");
});

test("uses custom transform function", async () => {
const collectionRef = collection(firestore, "tests");

await addDoc(collectionRef, { value: 10 });
await addDoc(collectionRef, { value: 20 });

const customTransform = (snapshot: QuerySnapshot<DocumentData>) => {
return snapshot.docs?.map((doc) => doc.data().value);
};

const { result } = renderHook(
() =>
useNamedQuery<number[]>(collectionRef, {
queryKey: ["named", "transform"],
firestore: {
transform: customTransform,
},
}),
{ wrapper }
);

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

expect(result?.current?.data).toEqual([10, 20]);
});

test("returns pending state initially", async () => {
const collectionRef = collection(firestore, "tests");

await addDoc(collectionRef, { value: 10 });

const { result } = renderHook(
() =>
useNamedQuery(collectionRef, {
queryKey: ["named", "pending"],
}),
{ wrapper }
);

// Initially isPending should be true
expect(result.current.isPending).toBe(true);

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

expect(result.current.data?.empty).toBe(false);
expect(result.current.data?.docs.length).toBe(1);
});
});
35 changes: 35 additions & 0 deletions packages/react/src/firestore/useNamedQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useQuery, type UseQueryOptions } from "@tanstack/react-query";
import {
type FirestoreError,
getDocs,
type Query,
type QuerySnapshot,
type DocumentData,
} from "firebase/firestore";

type FirestoreUseQueryOptions<TData = unknown, TError = Error> = Omit<
UseQueryOptions<TData, TError>,
"queryFn"
> & {
firestore?: {
transform?: (snapshot: QuerySnapshot<DocumentData>) => TData;
};
};

export function useNamedQuery<TData = QuerySnapshot<DocumentData>>(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't this hook is right... it should return a Query (or null) based on https://firebase.google.com/docs/reference/js/firestore_.md#namedquery_6438876

useNamedQuery(firestore, 'foo', { ... });

query: Query,
options: FirestoreUseQueryOptions<TData, FirestoreError>
) {
const { firestore, ...queryOptions } = options;

return useQuery<TData, FirestoreError>({
...queryOptions,
queryFn: async () => {
const snapshot = await getDocs(query);
if (firestore?.transform) {
return firestore.transform(snapshot);
}
return snapshot as TData;
},
});
}
Loading