Skip to content

🧹 [コードの健全性向上] Dashboard APIルートの共通処理をリファクタリング#177

Open
is0692vs wants to merge 2 commits intomainfrom
jules-12487929405010469319-17cad98c
Open

🧹 [コードの健全性向上] Dashboard APIルートの共通処理をリファクタリング#177
is0692vs wants to merge 2 commits intomainfrom
jules-12487929405010469319-17cad98c

Conversation

@is0692vs
Copy link
Copy Markdown
Contributor

@is0692vs is0692vs commented Apr 17, 2026

🎯 What: DashboardのAPIルート(summary, stats, year)で重複していたNextAuthのセッション取得・認証チェック、およびエラーハンドリング処理を src/lib/apiUtils.tsgetAuthenticatedUserhandleErrorResponse ヘルパー関数に抽出しました。
💡 Why: 同一の認証とエラー処理のボイラープレートが各ファイルに存在しており、関数の長大化と可読性の低下を招いていました。ヘルパー関数に集約することで、将来的な認証フローやエラー応答の変更を一箇所で行えるようになり、保守性と可読性が向上します。
Verification: npm run lint および npm run test -- --run を実行し、既存のテスト(特に各ルートの .test.ts)がすべて通過することを確認しました。また、各ルートからのレスポンス内容が変更前と同一であることを保証しています。
Result: 各APIルートがシンプルになり、データ取得のコアロジックに集中できる見通しの良いコードになりました。


PR created automatically by Jules for task 12487929405010469319 started by @is0692vs

Greptile Summary

Dashboard APIの3ルート(summarystatsyear)で重複していた NextAuth セッション取得・ユーザー名解決・エラー処理を src/lib/apiUtils.tsgetAuthenticatedUserhandleErrorResponse に集約したリファクタリングです。ロジックの変更はなく、挙動は既存コードと等価です(むしろ getServerSession 自体が例外を投げた場合も catch で捕捉されるため、堅牢性は微増)。

  • handleErrorResponse はサーバー側でエラーをログ出力していないため、本番で 500 が発生してもデバッグ情報が残りません。console.error(error) 等を追加することを検討してください(既存コードも同様でしたが、一元化した今がベストな改善タイミングです)。

Confidence Score: 5/5

マージ安全。既存の挙動を保ったままリファクタリングされており、テストも通過済みです。

P0/P1 の問題は見当たりません。残る指摘はエラーログ追加という P2 レベルの改善提案のみです。

特に問題のあるファイルはありませんが、src/lib/apiUtils.tshandleErrorResponse にサーバー側ログ出力を追加することを推奨します。

Important Files Changed

Filename Overview
src/lib/apiUtils.ts 新規ヘルパーファイル。getAuthenticatedUser は認証チェックとユーザー名解決を担い、handleErrorResponse はエラーを 500 レスポンスに変換する。エラーのサーバー側ログ出力が欠如している点が惜しい。
src/app/api/dashboard/stats/route.ts ボイラープレートを apiUtils に委譲し、年バリデーションとヒートマップ取得のコアロジックのみが残る。挙動に変更なし。
src/app/api/dashboard/summary/route.ts 認証・エラー処理を apiUtils に委譲。username: user.username の明示的なプロパティ名も正しく保持されている。
src/app/api/dashboard/year/route.ts stats/route.ts と同パターンでリファクタリング済み。挙動に変更なし。

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[クライアントリクエスト] --> B[API Route]
    B --> C[getAuthenticatedUser]
    C --> D{セッション有効?}
    D -- No --> E[401 Unauthorized]
    D -- Yes --> F{user.login あり?}
    F -- No --> G[fetchViewerLogin]
    G --> H[username 取得]
    F -- Yes --> H
    H --> I[user object 返却]
    I --> J[データ取得ロジック]
    J --> K{成功?}
    K -- Yes --> L[200 JSON]
    K -- No --> M[handleErrorResponse]
    M --> N[500 JSON]
Loading
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/lib/apiUtils.ts
Line: 18-21

Comment:
**エラーのサーバー側ログ出力が欠如しています**

`handleErrorResponse` はエラーメッセージをそのままクライアントへ返しますが、サーバー側へのログ出力がないため、本番環境で 500 エラーが発生してもスタックトレースや詳細が残りません。一元化した今がこの改善を入れるベストタイミングです。

```suggestion
export function handleErrorResponse(error: unknown) {
    console.error("[handleErrorResponse]", error);
    const message = error instanceof Error ? error.message : "Unknown error";
    return NextResponse.json({ error: message }, { status: 500 });
}
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "🧹 [コードの健全性向上] Dashboard APIルートの共通処理をリファ..." | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@vercel
Copy link
Copy Markdown

vercel bot commented Apr 17, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
github-user-summary Ready Ready Preview, Comment Apr 17, 2026 8:42am

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 17, 2026

Warning

Rate limit exceeded

@is0692vs has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 20 minutes and 42 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 20 minutes and 42 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 386b362e-8dfb-458e-a1ad-a664ce6eb2f4

📥 Commits

Reviewing files that changed from the base of the PR and between 3be157d and d3f8236.

📒 Files selected for processing (4)
  • src/app/api/dashboard/stats/route.ts
  • src/app/api/dashboard/summary/route.ts
  • src/app/api/dashboard/year/route.ts
  • src/lib/apiUtils.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jules-12487929405010469319-17cad98c

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@dosubot dosubot bot added the enhancement New feature or request label Apr 17, 2026
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 17, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the dashboard API routes by centralizing authentication and error handling into a new utility file, src/lib/apiUtils.ts. This change reduces code duplication across the stats, summary, and year endpoints. Feedback suggests further improving the handleErrorResponse function to support dynamic status codes and error logging, as well as extracting the duplicated year parameter validation logic into a shared utility.

Comment thread src/lib/apiUtils.ts
Comment thread src/app/api/dashboard/stats/route.ts
Comment thread src/lib/apiUtils.ts
Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant