Skip to content

Commit

Permalink
resultで過去の結果か未来の結果だけを取得するパラメータを追加
Browse files Browse the repository at this point in the history
  • Loading branch information
MurakawaTakuya committed Dec 1, 2024
1 parent 9a70bb0 commit 34103ff
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 61 deletions.
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,12 +227,14 @@ API is provided by Firebase Cloud Functions. Database is provided by Firestore.
## Result
### Get Result
- URL: /result/:userId
- Empty userId will return all results
- Empty userId will return all results.
- Parameters
- limit?: number - The maximum number of results to return.
- limit?: number - The maximum number of results to return.(Default is 10)
- offset?: number - The number of results to skip before starting to collect the result set.
- TODO: onlyPast?: boolean - If true, only past results will be returned.
- TODO: onlyFuture?: boolean - If true, only future results will be returned.
- onlyPast?: boolean - If true, only past results will be returned.
- onlyFuture?: boolean - If true, only future results will be returned.
- Example1: /result/:userId?limit=30&offset=0&onlyPast
- Example2: /result/:userId?onlyFuture
- Method: GET
- Response
```json
Expand All @@ -249,7 +251,7 @@ API is provided by Firebase Cloud Functions. Database is provided by Firestore.
"submittedAt": "2024-12-28T23:59:59.000Z"
}
],
"failedOrPendingPosts": [ // TODO: Posts -> Results
"failedOrPendingResults": [
{
"goalId": "0qVTLfKJ80m50XD5HAOI",
"userId": "FZ5KQ4sv0wZCow0MdwniPbyeBvVv",
Expand Down
5 changes: 2 additions & 3 deletions functions/src/routers/goalRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ router.get("/:userId", async (req: Request, res: Response) => {

// POST: 新しい目標を作成
router.post("/", async (req: Request, res: Response) => {
const goalId = db.collection("goal").doc().id; // FirebaseのドキュメントIDを生成
const goalId = db.collection("goal").doc().id;

let userId: Goal["userId"];
let deadline: Goal["deadline"];
Expand All @@ -82,7 +82,6 @@ router.post("/", async (req: Request, res: Response) => {
}

try {
// goalId をドキュメント名として使用してデータを保存
await db
.collection("goal")
.doc(goalId)
Expand Down Expand Up @@ -113,7 +112,7 @@ router.put("/:goalId", async (req: Request, res: Response) => {

const updateData: Partial<Omit<Goal, "deadline">> & {
deadline?: admin.firestore.Timestamp;
} = {}; // 型エラーが出たため書き方変更
} = {};
if (userId) updateData.userId = userId;
if (deadline)
updateData.deadline = admin.firestore.Timestamp.fromDate(
Expand Down
2 changes: 1 addition & 1 deletion functions/src/routers/postRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ router.get("/:userId", async (req: Request, res: Response) => {

// POST: 新しい投稿を作成し、画像をStorageに保存
router.post("/", async (req: Request, res: Response) => {
const postId = db.collection("post").doc().id; // FirebaseのドキュメントIDを生成
const postId = db.collection("post").doc().id;

let userId: Post["userId"];
let storedId: Post["storedId"];
Expand Down
70 changes: 35 additions & 35 deletions functions/src/routers/resultRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,26 @@ import { GoalWithId, SuccessResult } from "./types";
const router = express.Router();
const db = admin.firestore();

const getResults = async (limit: number, offset: number, userId?: string) => {
const getResults = async (
limit: number,
offset: number,
userId?: string,
onlyPast?: boolean, // 過去の結果のみ取得
onlyFuture?: boolean // 未来の結果のみ取得
) => {
let goalQuery = db.collection("goal").limit(limit).offset(offset);
if (userId) {
goalQuery = goalQuery.where("userId", "==", userId);
}
// TODO: 日本時間に合っているか確認
if (onlyPast) {
console.log("onlyPast");
goalQuery = goalQuery.where("deadline", "<", new Date());
}
if (onlyFuture) {
console.log("onlyFuture");
goalQuery = goalQuery.where("deadline", ">", new Date());
}
const goalSnapshot = await goalQuery.get();

const goals = goalSnapshot.docs.map((doc) => {
Expand Down Expand Up @@ -66,45 +81,30 @@ const getResults = async (limit: number, offset: number, userId?: string) => {
return { successResults, failedOrPendingResults };
};

// GET: 全ての目標に対する結果を取得
router.get("/", async (req: Request, res: Response) => {
try {
const limit = req.query.limit ? Number(req.query.limit) : 10; // 取得数
const offset = req.query.offset ? Number(req.query.offset) : 0; // 開始位置
if (offset < 0) {
res.status(400).json({ message: "Offset must be a positive number" });
}
if (limit < 1) {
res.status(400).json({ message: "Limit must be more than zero" });
}

const results = await getResults(limit, offset);
res.json(results);
} catch (error) {
console.error(error);
res.status(500).json({ message: "Internal server error" });
}
});

// GET: userIdから結果を取得
router.get("/:userId", async (req: Request, res: Response) => {
// GET: 全ての目標または特定のユーザーの目標に対する結果を取得
router.get("/:userId?", async (req: Request, res: Response) => {
const userId = req.params.userId;

if (!userId) {
res.status(400).json({ message: "User ID is required" });
const limit = req.query.limit ? Number(req.query.limit) : 10; // 取得数
const offset = req.query.offset ? Number(req.query.offset) : 0; // 開始位置
const onlyPast = req.query.onlyPast !== undefined; // 過去の結果のみ取得
const onlyFuture = req.query.onlyFuture !== undefined; // 未来の結果のみ取得
console.log(onlyPast, onlyFuture);
if (offset < 0) {
res.status(400).json({ message: "Offset must be a positive number" });
}
if (limit < 1) {
res.status(400).json({ message: "Limit must be more than zero" });
}

try {
const limit = req.query.limit ? Number(req.query.limit) : 10; // 取得数
const offset = req.query.offset ? Number(req.query.offset) : 0; // 開始位置
if (offset < 0) {
res.status(400).json({ message: "Offset must be a positive number" });
}
if (limit < 1) {
res.status(400).json({ message: "Limit must be more than zero" });
}

const results = await getResults(limit, offset, userId);
const results = await getResults(
limit,
offset,
userId,
onlyPast,
onlyFuture
);
res.json(results);
} catch (error) {
console.error(error);
Expand Down
10 changes: 0 additions & 10 deletions functions/src/routers/userRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,17 +85,7 @@ router.post("/", async (req: Request, res: Response) => {
return res.status(400).json({ message: "name and uid are required" });
}

// 既に同じ名前のuserが存在する場合はエラーを返す
// const userSnapshot = await getUserFromName(name);

// if (!userSnapshot.empty) {
// return res.status(409).json({
// message: `A user with the same user name '${name}' already exists`,
// });
// }

try {
// userIdをドキュメント名として使用してデータを保存
await db.collection("user").doc(uid).set({
name: name,
streak: streak,
Expand Down
9 changes: 2 additions & 7 deletions src/Components/DashBoard/DashBoard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default function DashBoard() {
const [noResult, setNoResult] = useState<boolean>(false);

useEffect(() => {
fetch(`${functionsEndpoint}/result/`)
fetch(`${functionsEndpoint}/result/?onlyPast`)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
Expand All @@ -28,7 +28,7 @@ export default function DashBoard() {
} else {
console.log(data);
setSuccessResults(data.successResults);
setFailedResults(data.failedResults);
setFailedResults(data.failedOrPendingResults);
}
})
.catch((error) => {
Expand All @@ -40,11 +40,6 @@ export default function DashBoard() {
});
}, []);

useEffect(() => {
console.log("successResults", successResults);
console.log("failedResults", failedResults);
}, [successResults, failedResults]);

return (
<>
{noResult ? (
Expand Down

0 comments on commit 34103ff

Please sign in to comment.