Skip to content

Commit

Permalink
storageの保存方法の変更とpost削除時にstorageの画像を削除するように変更
Browse files Browse the repository at this point in the history
  • Loading branch information
MurakawaTakuya committed Dec 29, 2024
1 parent 6d10172 commit 6d1a1cb
Show file tree
Hide file tree
Showing 10 changed files with 95 additions and 32 deletions.
8 changes: 4 additions & 4 deletions Documents/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ API is provided by Firebase Cloud Functions. Database is provided by Firestore.
"text": "hoge fuga",
"post": {
"userId": "Vlx6GCtq90ag3lxgh0pcCKGp5ba0",
"storedURL": "hogehoge URL",
"storedURL": "0f9a84ed-8ae8-44b0-a6f5-5ac5ca517948",
"text": "数学の勉強したよ^^",
"submittedAt": {
"_seconds": 1735603199,
Expand Down Expand Up @@ -158,7 +158,7 @@ API is provided by Firebase Cloud Functions. Database is provided by Firestore.
{
"goalId": "RXlHJiv3GtpzSDHhfljS",
"text": "今日は勉強をがんばった",
"storedURL": "hogehoge URL",
"storedURL": "0f9a84ed-8ae8-44b0-a6f5-5ac5ca517948",
"submittedAt": "2024-12-31T23:59:59.000Z"
}
```
Expand All @@ -182,7 +182,7 @@ API is provided by Firebase Cloud Functions. Database is provided by Firestore.
"goalId": "9fgWJA6wMN54EkxIC2WD",
"userId": "IK0Zc2hoUYaYjXoqzmCl",
"text": "今日は勉強をがんばった",
"storedURL": "hogehoge URL",
"storedURL": "0f9a84ed-8ae8-44b0-a6f5-5ac5ca517948",
"goalId": "RXlHJiv3GtpzSDHhfljS",
"submittedAt": "2024-12-31T23:59:59.000Z"
}
Expand Down Expand Up @@ -215,7 +215,7 @@ Use Create Post API to update post.
"text": "Duolingoやる",
"post": {
"text": "フランス語したよ",
"storedURL": "hogehoge URL",
"storedURL": "0f9a84ed-8ae8-44b0-a6f5-5ac5ca517948",
"submittedAt": "2024-12-28T09:45:10.718Z"
},
"userData": {
Expand Down
2 changes: 1 addition & 1 deletion functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import serviceAccount from "./serviceAccountKey.json";

admin.initializeApp({
credential: admin.credential.cert(serviceAccount as admin.ServiceAccount),
storageBucket: "todo-real-c28fa.appspot.com",
storageBucket: "todo-real-c28fa.firebasestorage.app",
});

import goalRouter from "./routers/goalRouter";
Expand Down
35 changes: 28 additions & 7 deletions functions/src/routers/goalRouter.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express, { Request, Response } from "express";
import admin from "firebase-admin";
import { logger } from "firebase-functions";
import { Goal, GoalWithId } from "./types";
import { Goal, GoalWithId } from "../types";

const router = express.Router();
const db = admin.firestore();
Expand Down Expand Up @@ -147,14 +147,35 @@ router.put("/:goalId", async (req: Request, res: Response) => {

// DELETE: 目標を削除
router.delete("/:goalId", async (req: Request, res: Response) => {
const goalId = req.params.goalId;
try {
const goalId = req.params.goalId;

if (!goalId) {
return res.status(400).json({ message: "Goal ID is required" });
}
if (!goalId) {
return res.status(400).json({ message: "Goal ID is required" });
}

try {
await db.collection("goal").doc(goalId).delete();
const goalRef = db.collection("goal").doc(goalId);
const goalDoc = await goalRef.get();

if (!goalDoc.exists) {
return res.status(404).json({ message: "Goal not found" });
}

// storageから画像を削除
const storedId = goalDoc.data()?.post?.storedId;
if (storedId) {
try {
const bucket = admin.storage().bucket();
const file = bucket.file(`post/${storedId}`);
await file.delete();
logger.info("Image deleted successfully:", storedId);
} catch (error) {
logger.error("Error deleting image:", error);
return res.status(500).json({ message: "Error deleting image" });
}
}

await goalRef.delete();
return res.json({ message: "Goal deleted successfully", goalId });
} catch (error) {
logger.error(error);
Expand Down
28 changes: 23 additions & 5 deletions functions/src/routers/postRouter.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import express, { Request, Response } from "express";
import admin from "firebase-admin";
import { logger } from "firebase-functions";
import { updateStreak } from "./status";
import { PostWithGoalId } from "./types";
import { updateStreak } from "../status";
import { PostWithGoalId } from "../types";

const router = express.Router();
const db = admin.firestore();
Expand Down Expand Up @@ -135,18 +135,36 @@ router.post("/", async (req: Request, res: Response) => {

// DELETE: 投稿を削除
router.delete("/:goalId", async (req: Request, res: Response) => {
const goalId = req.params.goalId;

try {
const goalId = req.params.goalId;

if (!goalId) {
return res.status(400).json({ message: "Goal ID is required" });
}

const goalRef = db.collection("goal").doc(goalId);
const goalDoc = await goalRef.get();

if (!goalDoc.exists) {
return res.status(404).json({ message: "Goal not found" });
}

// Storageから画像を削除
const storedURL = goalDoc.data()?.post?.storedURL;
if (storedURL) {
try {
const bucket = admin.storage().bucket();
const file = bucket.file(`post/${storedURL}`);
await file.delete();
logger.info("Image deleted successfully:", storedURL);
} catch (error) {
logger.error("Error deleting image:", error);
return res.status(500).json({ message: "Error deleting image" });
}
}

await goalRef.update({
post: admin.firestore.FieldValue.delete(),
post: null,
});

return res.json({ message: "Post deleted successfully" });
Expand Down
4 changes: 2 additions & 2 deletions functions/src/routers/resultRouter.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import express, { Request, Response } from "express";
import admin from "firebase-admin";
import { logger } from "firebase-functions";
import { countCompletedGoals, countFailedGoals, getStreak } from "./status";
import { GoalWithIdAndUserData, User } from "./types";
import { countCompletedGoals, countFailedGoals, getStreak } from "../status";
import { GoalWithIdAndUserData, User } from "../types";

const router = express.Router();
const db = admin.firestore();
Expand Down
23 changes: 15 additions & 8 deletions functions/src/routers/userRouter.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import express, { Request, Response } from "express";
import admin from "firebase-admin";
import { logger } from "firebase-functions";
import { countCompletedGoals, countFailedGoals, getStreak } from "./status";
import { User } from "./types";
import { countCompletedGoals, countFailedGoals, getStreak } from "../status";
import { User } from "../types";

const router = express.Router();
const db = admin.firestore();
Expand Down Expand Up @@ -179,14 +179,21 @@ router.put("/:userId", async (req: Request, res: Response) => {

// DELETE: ユーザーを削除
router.delete("/:userId", async (req: Request, res: Response) => {
const userId = req.params.userId;
try {
const userId = req.params.userId;

if (!userId) {
return res.status(400).json({ message: "User ID is required" });
}
if (!userId) {
return res.status(400).json({ message: "User ID is required" });
}

try {
await db.collection("user").doc(userId).delete();
const userRef = db.collection("user").doc(userId);
const userDoc = await userRef.get();

if (!userDoc.exists) {
return res.status(404).json({ message: "User not found" });
}

await userRef.delete();
return res.json({ message: "User deleted successfully", userId });
} catch (error) {
logger.error(error);
Expand Down
File renamed without changes.
File renamed without changes.
4 changes: 2 additions & 2 deletions src/Components/PostModal/PostModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,10 @@ export default function PostModal({
await uploadImage(
image,
(percent) => setProgress(percent),
async (url) => {
async (url, id) => {
const postData: PostWithGoalId = {
userId: user?.userId as string,
storedURL: url,
storedURL: id,
text: text,
goalId: goalId,
submittedAt: new Date(),
Expand Down
23 changes: 20 additions & 3 deletions src/Components/Progress/Progress.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import StepIndicator, { stepIndicatorClasses } from "@mui/joy/StepIndicator";
import Stepper from "@mui/joy/Stepper";
import Typography, { typographyClasses } from "@mui/joy/Typography";
import { Divider } from "@mui/material";
import { getDownloadURL, getStorage, ref } from "firebase/storage";
import { ReactNode, useState } from "react";
import DeleteGoalModal from "../DeleteGoalModal/DeleteGoalModal";
import DeletePostModal from "../DeletePostModal/DeletePostModal";
Expand Down Expand Up @@ -115,11 +116,27 @@ const SuccessStep = ({
result: GoalWithIdAndUserData;
user: User;
}) => {
const [imageURL, setImageURL] = useState("");
const [imageLoading, setImageLoading] = useState(true);

const post = result.post;
if (!post) {
return null;
}

const storage = getStorage();
const imageRef = ref(storage, `post/${post.storedURL}`);

getDownloadURL(imageRef)
.then((url) => {
console.log("Image URL:", url);
setImageURL(url);
setImageLoading(false);
})
.catch((error) => {
console.error("Error fetching image URL:", error);
});

return (
<StepperBlock
key={result.goalId}
Expand Down Expand Up @@ -164,10 +181,10 @@ const SuccessStep = ({
zIndex: 0,
}}
>
{post.storedURL && (
{!imageLoading && (
<img
src={post.storedURL}
srcSet={post.storedURL}
src={imageURL}
srcSet={imageURL}
style={{
objectFit: "contain",
maxWidth: "100%",
Expand Down

0 comments on commit 6d1a1cb

Please sign in to comment.