Skip to content

Commit

Permalink
Merge pull request #30 from toririm/issue/15-2
Browse files Browse the repository at this point in the history
`itemRepository`実装
  • Loading branch information
Lailai0477 authored Aug 27, 2024
2 parents cdb88f8 + 8a6e564 commit 8bc1e59
Showing 1 changed file with 42 additions and 20 deletions.
62 changes: 42 additions & 20 deletions app/repositories/item.ts
Original file line number Diff line number Diff line change
@@ -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());
},
};

0 comments on commit 8bc1e59

Please sign in to comment.