Skip to content

Commit

Permalink
Merge pull request #163 from MurakawaTakuya/feat/142-result-useContext
Browse files Browse the repository at this point in the history
resultの結果をuseEffectからuseContextに移行
  • Loading branch information
MurakawaTakuya authored Jan 16, 2025
2 parents 6dacf9b + 9f46301 commit e0070a1
Show file tree
Hide file tree
Showing 24 changed files with 456 additions and 138 deletions.
5 changes: 4 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,8 @@
"sourceType": "module"
},
"plugins": ["react", "eslint-plugin-unused-imports"],
"rules": { "unused-imports/no-unused-imports": "error" }
"rules": {
"unused-imports/no-unused-imports": "error",
"@next/next/no-img-element": "off"
}
}
2 changes: 1 addition & 1 deletion Documents/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ Use Create Post API to update post.
- URL: /result/:?userId
- Empty userId will return all results.
- Parameters
- limit?: number - The maximum number of results to return. (Default is 50)
- limit?: number - The maximum number of results to return. (Default is 50, successはlimit分取得し、そこに追加でfailedを取得する形になる)
- offset?: number - The number of results to skip before starting to collect the result set.
- onlyPending?: boolean - If true, only pending goals will be returned. (Default is false)
- onlyCompleted?: boolean - If true, only completed or failed goals will be returned. (Default is false)
Expand Down
25 changes: 13 additions & 12 deletions functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,31 +64,31 @@ if (process.env.NODE_ENV === "production") {
});
}

// 10分間で最大100回に制限
// 10分間で最大200回に制限
app.use(
rateLimit({
windowMs: 10 * 60 * 1000,
max: 100,
keyGenerator: (req) => {
const key = req.headers["x-forwarded-for"] || req.ip || "unknown";
return Array.isArray(key) ? key[0] : key;
},
max: 200,
// keyGenerator: (req) => {
// const key = req.headers["x-forwarded-for"] || req.ip || "unknown";
// return Array.isArray(key) ? key[0] : key;
// },
handler: (req, res) => {
return res
.status(429)
.json({ message: "Too many requests, please try again later." });
},
})
);
// 1時間で最大300回に制限
// 1時間で最大500回に制限
app.use(
rateLimit({
windowMs: 60 * 60 * 1000,
max: 300,
keyGenerator: (req) => {
const key = req.headers["x-forwarded-for"] || req.ip || "unknown";
return Array.isArray(key) ? key[0] : key;
},
max: 500,
// keyGenerator: (req) => {
// const key = req.headers["x-forwarded-for"] || req.ip || "unknown";
// return Array.isArray(key) ? key[0] : key;
// },
handler: (req, res) => {
return res
.status(429)
Expand Down Expand Up @@ -160,6 +160,7 @@ export const beforecreated = beforeUserCreated(
streak: 0,
fcmToken: "",
});
logger.info(`User data created for ${userId}`);
} catch (error) {
logger.error(error);
throw new HttpsError("internal", "Error creating user data.");
Expand Down
18 changes: 18 additions & 0 deletions functions/src/routers/resultRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const getResults = async (

const userList = new Map<string, User>(); // ユーザー情報のキャッシュ

// これからの目標のみ
if (onlyPending || (!onlyPending && !onlyFinished)) {
const pendingSnapshot = await baseQuery
.where("post", "==", null)
Expand All @@ -52,15 +53,30 @@ const getResults = async (
pendingResults.push(...pendingGoals);
}

// 完了・失敗した目標のみ
if (onlyFinished || (!onlyPending && !onlyFinished)) {
const completedSnapshot = await baseQuery
.where("post", "!=", null)
.orderBy("post.submittedAt", "desc") // 新しいものが先
.get();

// completedSnapshotをsubmittedAtでソートして最も昔の日時を取得
const earliestSubmittedAt = completedSnapshot.docs
.map((doc) => doc.data().post.submittedAt)
.sort((a, b) => a.toDate().getTime() - b.toDate().getTime())[0];

if (!earliestSubmittedAt) {
return {
successResults,
failedResults,
pendingResults,
};
}

const failedSnapshot = await baseQuery
.where("post", "==", null)
.where("deadline", "<=", now)
.where("deadline", ">", earliestSubmittedAt)
.orderBy("deadline", "desc") // 新しいものが先
.get();

Expand All @@ -81,6 +97,7 @@ const getResults = async (
};
};

// ユーザーデータを組み込む
const processGoals = async (
docs: FirebaseFirestore.QueryDocumentSnapshot[],
userList: Map<string, User>
Expand Down Expand Up @@ -128,6 +145,7 @@ const processGoals = async (
};

// GET: 全ての目標または特定のユーザーの目標に対する結果を取得
// onlyFinishedの場合のlimitはsuccessをlimitの数返してその期間内のfailedを追加で返す
router.get("/:userId?", async (req: Request, res: Response) => {
const userId = req.params.userId;

Expand Down
3 changes: 2 additions & 1 deletion functions/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@
"skipLibCheck": true
},
"compileOnSave": true,
"include": ["src/*", "functions/src/**/*", "src/**/*.ts"]
"include": ["src/*", "functions/src/**/*", "src/**/*.ts"],
"exclude": ["node_modules"]
}
Binary file modified public/img/blur.webp
Binary file not shown.
9 changes: 8 additions & 1 deletion src/Components/Account/LoggedInView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,14 @@ export default function LoggedInView() {
</Typography>
) : (
<>
<Typography level="body-lg" sx={{ textAlign: "center" }}>
<Typography
level="body-lg"
sx={{
textAlign: "center",
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
ようこそ、{user.name}さん!
</Typography>
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { showSnackBar } from "@/Components/SnackBar/SnackBar";
import { PostWithGoalId } from "@/types/types";
import { createPost, handleCreatePostError } from "@/utils/API/Post/createPost";
import { useAddPost } from "@/utils/ResultContext";
import { removeImageMetadata, uploadImage } from "@/utils/Uploader";
import { useUser } from "@/utils/UserContext";
import { Add } from "@mui/icons-material";
Expand All @@ -24,20 +25,15 @@ import Typography from "@mui/material/Typography";
import { styled } from "@mui/material/styles";
import React, { ChangeEvent, useState } from "react";

export default function PostModal({
goalId,
setIsSubmitted,
}: {
goalId: string;
setIsSubmitted: React.Dispatch<React.SetStateAction<boolean>>;
}) {
export default function CreatePostModal({ goalId }: { goalId: string }) {
const [open, setOpen] = useState(false);
const [text, setText] = useState<string>("");
const [image, setImage] = useState<File | null>(null);
const [progress, setProgress] = useState<number>(100);
const [fileName, setFileName] = useState<string>("");
const [loading, setLoading] = useState<boolean>(false);
const { user } = useUser();
const addPost = useAddPost();

const handleTextChange = (event: ChangeEvent<HTMLInputElement>) => {
setText(event.target.value);
Expand All @@ -48,7 +44,7 @@ export default function PostModal({

if (!selectedFile) {
showSnackBar({
message: "ファイルが選択されていません",
message: "画像が選択されていません",
type: "warning",
});
return;
Expand Down Expand Up @@ -80,7 +76,7 @@ export default function PostModal({
const handleUpload = async () => {
if (!image) {
showSnackBar({
message: "ファイルが選択されていません",
message: "画像が選択されていません",
type: "warning",
});
return;
Expand Down Expand Up @@ -110,7 +106,12 @@ export default function PostModal({
message: "投稿しました",
type: "success",
});
setIsSubmitted(true);

const postDataWithStringDate = {
...postData,
submittedAt: (postData.submittedAt as Date).toISOString(),
};
addPost(goalId, postDataWithStringDate);

setImage(null);
setText("");
Expand Down
Loading

0 comments on commit e0070a1

Please sign in to comment.