diff --git a/app/repositories/item.ts b/app/repositories/item.ts index 967ebf40..b75ef7d7 100644 --- a/app/repositories/item.ts +++ b/app/repositories/item.ts @@ -1,30 +1,52 @@ -import { addDoc, collection, getDocs } from "firebase/firestore"; +import { addDoc, collection, deleteDoc, doc, getDoc, getDocs, setDoc } from "firebase/firestore"; import { converter } from "~/firebase/converter"; import { db } from "~/firebase/firestore"; -import { Item, itemSchema } from "~/models/item"; +import { hasId } from "~/lib/typeguard"; +import { itemSchema } from "~/models/item"; import { ItemRepository } from "./type"; export const itemRepository: ItemRepository = { - findAll: async () => { - const itemsRef = collection(db, "items").withConverter( - converter(itemSchema), - ); - const docSnap = await getDocs(itemsRef); - const items = docSnap.docs.map((doc) => doc.data()); - console.log(items); - return items; + save: async (item) => { + if (hasId(item)) { + const docRef = doc(db, "items", item.id).withConverter( + converter(itemSchema.required()), + ); + await setDoc(docRef, item); + return item; + } else { + const colRef = collection(db, "items").withConverter(converter(itemSchema)); + const docRef = await addDoc(colRef, item); + const resultDoc = await getDoc( + docRef.withConverter(converter(itemSchema.required())), + ); + if (resultDoc.exists()) { + return resultDoc.data(); + } + throw new Error("Failed to save item"); + } }, - findById: async (id: string) => { - // ここに Firestore からデータを取得する処理を記述 - return null; - }, - create: async (data: Item) => { - const docRef = await addDoc(collection(db, "items"), data); + + delete: async (id) => { + await deleteDoc(doc(db, "items", id)); }, - update: async (data: Item) => { - // ここに Firestore のデータを更新する処理を記述 + + findById: async (id) => { + const docRef = doc(db, "items", id).withConverter( + converter(itemSchema.required()) + ); + const docSnap = await getDoc(docRef); + if (docSnap.exists()) { + return docSnap.data(); + } else { + return null; + } }, - delete: async (id: string) => { - // ここに Firestore のデータを削除する処理を記述 + + findAll: async () => { + const colRef = collection(db, "items").withConverter( + converter(itemSchema.required()), + ); + const docSnaps = await getDocs(colRef); + return docSnaps.docs.map((doc) => doc.data()); }, };