From 629650fb13447f15326b6460055566cdc1852806 Mon Sep 17 00:00:00 2001 From: Ura Date: Sat, 26 Oct 2024 14:29:37 +0900 Subject: [PATCH] =?UTF-8?q?CRUD=E5=85=B1=E9=80=9A=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- task_yell/src/firebase/firestore.ts | 54 +++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 task_yell/src/firebase/firestore.ts diff --git a/task_yell/src/firebase/firestore.ts b/task_yell/src/firebase/firestore.ts new file mode 100644 index 0000000..66381bd --- /dev/null +++ b/task_yell/src/firebase/firestore.ts @@ -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 を拡張するように制約を追加 */ +export async function createData>( + collectionName: string, + data: T +): Promise { + const docRef = await addDoc(collection(db, collectionName), data); + return docRef.id; +} + +export async function readData(collectionName: string): Promise { + const snapshot = await getDocs(collection(db, collectionName)); + return snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as T)); +} + +export async function readSingleData( + collectionName: string, + id: string +): Promise { + const docRef = doc(db, collectionName, id); + const snapshot = await getDoc(docRef); + return snapshot.exists() ? (snapshot.data() as T) : null; +} + +export async function updateData( + collectionName: string, + id: string, + data: Partial +): Promise { + const docRef = doc(db, collectionName, id); + await updateDoc(docRef, data); +} + +export async function deleteData( + collectionName: string, + id: string +): Promise { + const docRef = doc(db, collectionName, id); + await deleteDoc(docRef); +}