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

BO45 - create a DAL utility to get data without pagination #263

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
129 changes: 129 additions & 0 deletions src/data/firestore/common/get-all-documents.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import type { GetAllDocumentsParam } from "~/models/get-all/get-all-document.type.ts";
import {
testConverter,
type TestDoc,
type TestModel,
} from "~/data/firestore/common/test-model.ts";
import { firestoreInstance } from "~/firebase/server.ts";
import { getAllDocuments } from "~/data/firestore/common/get-all-documents.ts";
import { fail } from "node:assert";
import type { FirestoreDataConverter } from "firebase-admin/firestore";

const testCollection = "test-collection";

describe("getAllDocuments", () => {
beforeEach(async () => {
const batch = firestoreInstance.batch();
const testData: Omit<TestModel, "id">[] = [
{ name: "Test 1", lastUpdate: new Date("2023-01-01") },
{ name: "Test 2", lastUpdate: new Date("2023-01-02") },
{ name: "Test 3", lastUpdate: new Date("2023-01-03") },
];
testData.forEach((data) => {
const docRef = firestoreInstance.collection(testCollection).doc();
batch.set(docRef, testConverter.toFirestore(data as TestModel));
});
await batch.commit();
});

afterEach(async () => {
const snapshot = await firestoreInstance.collection(testCollection).get();
const batch = firestoreInstance.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit();
});

test("should get all documents successfully", async () => {
const params: GetAllDocumentsParam<TestModel> = {
orderBy: "name",
orderDirection: "asc",
};

const result = await getAllDocuments(testCollection, testConverter, params);

expect(result.status).toBe("success");
expect(result.data).toHaveLength(3);
if (result.status === "success") {
expect(result.data).toHaveLength(3);
expect(result.data[0].name).toBe("Test 1");
expect(result.data[1].name).toBe("Test 2");
expect(result.data[2].name).toBe("Test 3");
expect(result.data[0].lastUpdate).toBeInstanceOf(Date);
expect(result.data[0].id).toBeDefined();
} else {
fail("Expected successful result");
}
});

test("should handle empty collection", async () => {
const snapshot = await firestoreInstance.collection(testCollection).get();
const batch = firestoreInstance.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit();

const params: GetAllDocumentsParam<TestModel> = {
orderBy: "name",
orderDirection: "desc",
};

const result = await getAllDocuments(testCollection, testConverter, params);

expect(result.status).toBe("success");
expect(result.data).toHaveLength(0);
});

test("should use correct ordering", async () => {
const params: GetAllDocumentsParam<TestModel> = {
orderBy: "lastUpdate",
orderDirection: "desc",
};

const result = await getAllDocuments(testCollection, testConverter, params);

expect(result.status).toBe("success");
expect(result.data).toHaveLength(3);
if (result.status === "success") {
expect(result.data[0].lastUpdate.getTime()).toBeGreaterThan(
result.data[1].lastUpdate.getTime(),
);
expect(result.data[1].lastUpdate.getTime()).toBeGreaterThan(
result.data[2].lastUpdate.getTime(),
);
} else {
fail("Expected successful result");
}
});

test("Should return an error if firestore error", async () => {
const fakeConverter: FirestoreDataConverter<TestModel, TestDoc> = {
toFirestore: (): TestDoc => {
throw new Error("Error converting to firestore");
},
fromFirestore: (): TestModel => {
throw new Error("Error converting from firestore");
},
};

const params: GetAllDocumentsParam<TestModel> = {
orderBy: "name",
orderDirection: "desc",
};

const result = await getAllDocuments(testCollection, fakeConverter, params);

expect(result.status).toBe("error");
if (result.status === "error") {
expect(result.data.code).toBe(`${testCollection}/get-all-error`);
expect(result.data.message).toBe(
`Error getting documents from collection: ${testCollection}`,
);
} else {
fail("Expected error result");
}
});
});
49 changes: 49 additions & 0 deletions src/data/firestore/common/get-all-documents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type {
DocumentData,
FirestoreDataConverter,
} from "firebase-admin/firestore";
import { firestoreInstance } from "~/firebase/server";
import type { BaseModel } from "~/models/base-model";
import type { ServerResponse } from "~/models/server-response/server-response.type";
import type { GetAllDocumentsParam } from "~/models/get-all/get-all-document.type.ts";

export const getAllDocuments = async <
M extends BaseModel,
D extends DocumentData,
P extends GetAllDocumentsParam<M>,
C extends string,
>(
collection: C,
converter: FirestoreDataConverter<M, D>,
params: P,
): Promise<
ServerResponse<
M[],
| `${C}/get-all-error`
>
> => {
try {
const snapshot = await firestoreInstance
.collection(collection)
.withConverter<M, D>(converter)
.orderBy(params.orderBy, params.orderDirection)
.get();
const data = snapshot.docs.map((doc) => doc.data());
return {
status: "success",
data: data,
};
} catch (error) {
console.error(
`Error getting documents from collection: ${collection}`,
error,
);
return {
status: "error",
data: {
code: `${collection}/get-all-error`,
message: `Error getting documents from collection: ${collection}`,
},
};
}
};
14 changes: 13 additions & 1 deletion src/models/base-model.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
type OrderDirection = "asc" | "desc";

type FlattenKeys<T> = T extends object
? {
[K in keyof T]-?: T[K] extends Date
? `${K & string}`
: K extends string | number | boolean
? `${K}` | `${K & string}.${FlattenKeys<T[K]>}`
: never;
}[keyof T]
: never;

type BaseModel = {
id?: string;
};

export type { BaseModel };
export type { OrderDirection, FlattenKeys, BaseModel };
8 changes: 8 additions & 0 deletions src/models/get-all/get-all-document.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import {z} from "astro/zod";

const getAllDocumentsParamsSchema = z.object({
orderBy: z.string(),
orderDirection: z.enum(["asc", "desc"]),
});

export {getAllDocumentsParamsSchema};
8 changes: 8 additions & 0 deletions src/models/get-all/get-all-document.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type {FlattenKeys, OrderDirection} from "~/models/base-model.ts";

type GetAllDocumentsParam<T> = {
orderBy: FlattenKeys<T>;
orderDirection: OrderDirection;
};

export type { GetAllDocumentsParam };
20 changes: 4 additions & 16 deletions src/models/pagination/pagination.type.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { GetAllDocumentsParam } from "~/models/get-all/get-all-document.type.ts";

type PaginatedResponse<T> = {
data: T[];
total: number;
Expand All @@ -6,23 +8,9 @@ type PaginatedResponse<T> = {
totalPages: number;
};

type PaginationParams<T> = {
orderBy: FlattenKeys<T>;
orderDirection: OrderDirection;
type PaginationParams<T> = GetAllDocumentsParam<T> & {
offset: number;
limit: number;
};

type OrderDirection = "asc" | "desc";

type FlattenKeys<T> = T extends object
? {
[K in keyof T]-?: T[K] extends Date
? `${K & string}`
: K extends string | number | boolean
? `${K}` | `${K & string}.${FlattenKeys<T[K]>}`
: never;
}[keyof T]
: never;

export type { PaginatedResponse, PaginationParams, OrderDirection };
export type { PaginatedResponse, PaginationParams };
Loading