Skip to content

Commit

Permalink
Merge pull request #25 from jphacks/feature/#24
Browse files Browse the repository at this point in the history
CRUD共通化
  • Loading branch information
yuto-trd authored Oct 26, 2024
2 parents 17c40e9 + 629650f commit bf643c2
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions task_yell/src/firebase/firestore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// src/firebase/firestore.ts
import { db } from "./client-app";
import {
collection,
addDoc,
getDocs,
updateDoc,
deleteDoc,
doc,
//追加
WithFieldValue,
DocumentData,
getDoc,
} from "firebase/firestore";

/** dataが WithFieldValue<DocumentData> を拡張するように制約を追加 */
export async function createData<T extends WithFieldValue<DocumentData>>(
collectionName: string,
data: T
): Promise<string> {
const docRef = await addDoc(collection(db, collectionName), data);
return docRef.id;
}

export async function readData<T>(collectionName: string): Promise<T[]> {
const snapshot = await getDocs(collection(db, collectionName));
return snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as T));
}

export async function readSingleData<T>(
collectionName: string,
id: string
): Promise<T | null> {
const docRef = doc(db, collectionName, id);
const snapshot = await getDoc(docRef);
return snapshot.exists() ? (snapshot.data() as T) : null;
}

export async function updateData<T>(
collectionName: string,
id: string,
data: Partial<T>
): Promise<void> {
const docRef = doc(db, collectionName, id);
await updateDoc(docRef, data);
}

export async function deleteData(
collectionName: string,
id: string
): Promise<void> {
const docRef = doc(db, collectionName, id);
await deleteDoc(docRef);
}

0 comments on commit bf643c2

Please sign in to comment.