Skip to content

🧹 [code health] Extract HTTP status magic numbers to constants in github.ts#342

Open
is0692vs wants to merge 4 commits into
mainfrom
jules-2109023747470424910-39b6930a
Open

🧹 [code health] Extract HTTP status magic numbers to constants in github.ts#342
is0692vs wants to merge 4 commits into
mainfrom
jules-2109023747470424910-39b6930a

Conversation

@is0692vs

@is0692vs is0692vs commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

🎯 What: Extracted hardcoded HTTP status codes to a constant HTTP_STATUS object in src/lib/github.ts and replaced all magic numbers (400, 401, 403, 404).

💡 Why: Magic numbers like HTTP status codes are error-prone and harder to interpret quickly. Extracting them to named constants improves code readability, ensures consistency, and makes future maintenance easier.

Verification:

  • Modified code using bash script to patch exactly the necessary lines.
  • Verified diff to confirm the hardcoded values were successfully replaced with constant properties.
  • Ran npm run lint successfully.
  • Ran full test suite via npm run test which passed successfully (551 tests across 71 files).

Result: Improved maintainability of src/lib/github.ts by centralizing the definition of HTTP status codes used in error handling and API requests.


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

Greptile Summary

このPRは src/lib/github.ts 内のHTTPステータスコードのマジックナンバー(400, 401, 403, 404)を HTTP_STATUS 定数オブジェクトに集約し、ファイル内の全5箇所を置き換えたコードヘルス改善です。ロジックの変更はなく、リファクタリングのみです。

  • HTTP_STATUS 定数を as const で定義し、型安全性を確保しながら全使用箇所に適用した
  • headers(), handleResponse(), graphql(), fetchContributions() の各関数でマジックナンバーが削除された
  • 唯一の軽微な指摘は定数宣言直後の空行が二重になっている点のみ

Confidence Score: 4/5

純粋なリファクタリングであり、ロジックの変更はないためマージは安全です。

すべてのマジックナンバーが正しく定数に置き換えられており、as const による型安全性も確保されています。空行が二重になっている軽微なスタイル上の問題が1点あるのみで、機能への影響はありません。

特に注意が必要なファイルはありません。src/lib/github.ts の変更は意図通りに機能しています。

Important Files Changed

Filename Overview
src/lib/github.ts HTTP ステータスコード(400/401/403/404)を HTTP_STATUS 定数オブジェクトに抽出し、ファイル内の全5箇所のマジックナンバーを置き換えた。ロジックの変更は一切なく、スタイル上の空行二重のみが軽微な指摘点。

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[API レスポンス受信] --> B{ステータスコード確認}
    B -->|HTTP_STATUS.NOT_FOUND 404| C[UserNotFoundError をスロー]
    B -->|HTTP_STATUS.FORBIDDEN 403| D[handleRateLimit → RateLimitError]
    B -->|res.ok = false| E[GitHubApiError をスロー]
    B -->|res.ok = true| F[JSON パース & 返却]

    G[headers 関数] -->|不正なトークン形式| H[GitHubApiError HTTP_STATUS.BAD_REQUEST 400]
    I[graphql 関数] -->|トークンなし| J[GitHubApiError HTTP_STATUS.UNAUTHORIZED 401]
    I -->|HTTP_STATUS.FORBIDDEN 403| D
    K[fetchContributions] -->|トークンなし| L[GitHubApiError HTTP_STATUS.UNAUTHORIZED 401]
Loading
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
src/lib/github.ts:31-35
`HTTP_STATUS` 定数宣言の直後に空行が2行連続しています。コードスタイルの統一のため1行にまとめることを推奨します。

```suggestion
  NOT_FOUND: 404,
} as const;

export function headers(token?: string): HeadersInit {
```

Reviews (1): Last reviewed commit: "🧹 Extract hardcoded HTTP status codes t..." | 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

vercel Bot commented Jun 6, 2026

Copy link
Copy Markdown

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

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
github-user-summary Ignored Ignored Jun 6, 2026 4:53am

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Jun 6, 2026

Copy link
Copy Markdown

Wondering what really moved? Review this PR in Change Stack to inspect semantic changes, definitions, and references.

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

リリースノート

  • バグ修正

    • GitHub API エラーハンドリングを改善しました。無効なトークンやレート制限など、各種エラー状況での処理が強化されました。
  • テスト

    • GitHub API との連携に関するエラーシナリオのテストカバレッジを拡充しました。

Walkthrough

HTTP_STATUS定数(BAD_REQUEST/UNAUTHORIZED/FORBIDDEN/NOT_FOUND)を導入し、GitHub API エラーレスポンスの処理を統一化。graphql()token 引数を任意から必須に変更し、認証要件を厳格化。複数のエラーシナリオをカバーするテストケースを追加。

Changes

GitHub API エラーハンドリング改善

Layer / File(s) Summary
HTTP_STATUS定数の導入とエラーハンドリング統一
src/lib/github.ts
HTTP_STATUS定数を定義し、headers()handleResponse()graphql()fetchContributions()でステータスコード判定を数値直書きから定数参照に変更。graphql()token 引数を任意(token?: string)から必須(token: string)に変更し、認証チェック分岐を削除。
認証要件と定数検証テスト
src/lib/__tests__/github/fetchUserProfile.test.ts, src/lib/__tests__/github/fetchRepositories.test.ts
トークンなしの API 呼び出しで GitHubApiError が投げられること、HTTP_STATUS 定数の値が正しいこと、無効なトークン形式でエラーになること、無効トークン・403・401 などのレスポンスで適切な例外型が発生することを検証するテスト。

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • Hiroki-org/github-user-summary#139: 同じ認証不足エラーパスをターゲット。本PRではgithub.ts内のGraphQL/トークンエラーハンドリングを調整(HTTP_STATUS.UNAUTHORIZED使用、token必須化)、関連PRは401ステータスで例外を投げるテストを追加。

Poem

🐰 トークンを必ず持ちて、
定数で統一する道を歩む。
エラー定義も、見通し良好。
テストも充実、安心の品質。
🔐✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed プルリクエストのタイトルは、github.ts 内のHTTPステータスコードのマジックナンバーを定数に抽出するという変更内容を正確に反映しており、主な変更点を簡潔かつ明確に説明しています。
Description check ✅ Passed プルリクエストの説明は、マジックナンバーの抽出理由(可読性・保守性の向上)、検証方法(スクリプト、リント、テスト)、結果まで詳細に記載されており、変更内容と明確に関連しています。
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jules-2109023747470424910-39b6930a

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.

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

Copy link
Copy Markdown

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 src/lib/github.ts by introducing an HTTP_STATUS constant object to replace hardcoded HTTP status codes (400, 401, 403, and 404) with descriptive constants. The reviewer suggests extending this refactoring to include other hardcoded status codes (422 and 500) present elsewhere in the file to ensure complete consistency.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread src/lib/github.ts Outdated
Comment on lines +27 to +32
const HTTP_STATUS = {
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
} as const;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

To complete the extraction of HTTP status magic numbers in this file, consider also defining constants for 422 (Unprocessable Entity) and 500 (Internal Server Error) which are still hardcoded on lines 141 and 144 respectively. This ensures full consistency across github.ts.

Suggested change
const HTTP_STATUS = {
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
} as const;
const HTTP_STATUS = {
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
UNPROCESSABLE_ENTITY: 422,
INTERNAL_SERVER_ERROR: 500,
} as const;

@codecov

codecov Bot commented Jun 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Comment thread src/lib/github.ts
Comment on lines +31 to 35
NOT_FOUND: 404,
} as const;


export function headers(token?: string): HeadersInit {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 HTTP_STATUS 定数宣言の直後に空行が2行連続しています。コードスタイルの統一のため1行にまとめることを推奨します。

Suggested change
NOT_FOUND: 404,
} as const;
export function headers(token?: string): HeadersInit {
NOT_FOUND: 404,
} as const;
export function headers(token?: string): HeadersInit {
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/lib/github.ts
Line: 31-35

Comment:
`HTTP_STATUS` 定数宣言の直後に空行が2行連続しています。コードスタイルの統一のため1行にまとめることを推奨します。

```suggestion
  NOT_FOUND: 404,
} as const;

export function headers(token?: string): HeadersInit {
```

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@pull-request-size pull-request-size Bot added size/L and removed size/S labels Jun 6, 2026
…raints

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@pull-request-size pull-request-size Bot added size/M and removed size/L labels Jun 6, 2026
Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/__tests__/github/fetchRepositories.test.ts`:
- Around line 22-28: Update the tests that currently only assert the thrown
error type to also assert the GitHubApiError.status values: call
headers("invalid token format!!") and catch the thrown GitHubApiError
(referencing GitHubApiError and headers) and assert error.status === 400
(BAD_REQUEST) for the invalid-token-format test; similarly update the test that
simulates a 401 response to assert error.status === 401. Make the assertions by
capturing the thrown error (try/catch or expect(...).toThrow and then inspect
the thrown value) so the status field is explicitly checked alongside the type.

In `@src/lib/__tests__/github/fetchUserProfile.test.ts`:
- Around line 16-20: The test for fetchContributions currently only asserts that
it throws GitHubApiError but doesn't check the HTTP status; update the test that
imports fetchContributions and GitHubApiError to capture the thrown error (via
await expect(...).rejects.toThrow or try/catch) and assert that error.status ===
401 for the GraphQL no-token case (and similarly update the other test around
fetchContributions to assert error.status === 400 for the bad-request case),
referencing the GitHubApiError instance to read its status field.

In `@src/lib/github.ts`:
- Line 34: src/lib/github.ts 内の定数宣言の直後にある不要な空行を削除してください。ファイル内のすべての const
宣言(ファイル先頭やモジュールスコープにある const ...; や const <識別子> =
...;)を探し、定数宣言の直後にある単一の空行を取り除いてコードの一貫性を戻してください。該当箇所は "const"
キーワードを含む宣言を目印に修正してください。
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8eb7d4c4-5fd0-4325-944d-88617ac1b91b

📥 Commits

Reviewing files that changed from the base of the PR and between 4e9c001 and fa883bf.

📒 Files selected for processing (3)
  • src/lib/__tests__/github/fetchRepositories.test.ts
  • src/lib/__tests__/github/fetchUserProfile.test.ts
  • src/lib/github.ts

Comment on lines +22 to +28
it("GraphQL query fails when forbidden due to bad token", async () => {
// If token is missing, fetchRepositories doesn't throw, it falls back to REST API.
// What about an invalid token format?
const { headers } = await import("../../github");
const { GitHubApiError } = await import("../../types");
expect(() => headers("invalid token format!!")).toThrow(GitHubApiError);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

GitHubApiErrorのステータスコード検証を追加してください

エラー型の検証は実装されていますが、GitHubApiErrorstatusフィールドが期待値と一致することを確認するべきです。具体的には:

  • Lines 22-28 / 37-43: 不正なトークン形式ではstatus400 (BAD_REQUEST)であること
  • Lines 45-50: 401レスポンスではstatus401であること

コーディングガイドラインに従い、401、403などの具体的なステータスコードの検証が必要です。

♻️ 提案される修正例
  it("GraphQL query fails when forbidden due to bad token", async () => {
    const { headers } = await import("../../github");
    const { GitHubApiError } = await import("../../types");
-    expect(() => headers("invalid token format!!")).toThrow(GitHubApiError);
+    try {
+      headers("invalid token format!!");
+      expect.fail("Should have thrown");
+    } catch (e) {
+      expect(e).toBeInstanceOf(GitHubApiError);
+      expect((e as GitHubApiError).status).toBe(400);
+    }
  });
  it("GraphQL API throws GitHubApiError on 401 response", async () => {
    mockFetch.mockResolvedValueOnce(jsonResponse({ message: "Bad credentials" }, 401));
    const { fetchRepositories } = await import("../../github");
    const { GitHubApiError } = await import("../../types");
-    await expect(fetchRepositories("testuser", "fake-token")).rejects.toThrow(GitHubApiError);
+    try {
+      await fetchRepositories("testuser", "fake-token");
+      expect.fail("Should have thrown");
+    } catch (e) {
+      expect(e).toBeInstanceOf(GitHubApiError);
+      expect((e as GitHubApiError).status).toBe(401);
+    }
  });

Also applies to: 37-43, 45-50

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/__tests__/github/fetchRepositories.test.ts` around lines 22 - 28,
Update the tests that currently only assert the thrown error type to also assert
the GitHubApiError.status values: call headers("invalid token format!!") and
catch the thrown GitHubApiError (referencing GitHubApiError and headers) and
assert error.status === 400 (BAD_REQUEST) for the invalid-token-format test;
similarly update the test that simulates a 401 response to assert error.status
=== 401. Make the assertions by capturing the thrown error (try/catch or
expect(...).toThrow and then inspect the thrown value) so the status field is
explicitly checked alongside the type.

Source: Coding guidelines

Comment on lines +16 to +20
it("GraphQL API without token throws UNAUTHORIZED correctly through API error", async () => {
const { fetchContributions } = await import("../../github");
const { GitHubApiError } = await import("../../types");
await expect(fetchContributions("testuser")).rejects.toThrow(GitHubApiError);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

エラーテストでHTTPステータスコードの検証を追加してください

エラー型の検証は実装されていますが、GitHubApiErrorstatusフィールドの値が検証されていません。コーディングガイドラインに従い、401、403、404などの具体的なステータスコードを確認するべきです。

例:

  • Line 16-20のテストではerror.status401 (UNAUTHORIZED)であることを確認
  • Line 32-39のテストではerror.status400 (BAD_REQUEST)であることを確認
♻️ 提案される修正例
  it("GraphQL API without token throws UNAUTHORIZED correctly through API error", async () => {
    const { fetchContributions } = await import("../../github");
    const { GitHubApiError } = await import("../../types");
-    await expect(fetchContributions("testuser")).rejects.toThrow(GitHubApiError);
+    try {
+      await fetchContributions("testuser");
+      expect.fail("Should have thrown");
+    } catch (e) {
+      expect(e).toBeInstanceOf(GitHubApiError);
+      expect((e as GitHubApiError).status).toBe(401);
+    }
  });
  it("無効なトークンフォーマットの場合 GitHubApiError をスローする", async () => {
    const { fetchUserProfile } = await import("../../github");
    const { GitHubApiError } = await import("../../types");

-    await expect(fetchUserProfile("testuser", "invalid token with spaces")).rejects.toThrow(
-      GitHubApiError
-    );
+    try {
+      await fetchUserProfile("testuser", "invalid token with spaces");
+      expect.fail("Should have thrown");
+    } catch (e) {
+      expect(e).toBeInstanceOf(GitHubApiError);
+      expect((e as GitHubApiError).status).toBe(400);
+    }
  });

Also applies to: 32-39

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/__tests__/github/fetchUserProfile.test.ts` around lines 16 - 20, The
test for fetchContributions currently only asserts that it throws GitHubApiError
but doesn't check the HTTP status; update the test that imports
fetchContributions and GitHubApiError to capture the thrown error (via await
expect(...).rejects.toThrow or try/catch) and assert that error.status === 401
for the GraphQL no-token case (and similarly update the other test around
fetchContributions to assert error.status === 400 for the bad-request case),
referencing the GitHubApiError instance to read its status field.

Source: Coding guidelines

Comment thread src/lib/github.ts
NOT_FOUND: 404,
} as const;


Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial | 💤 Low value

定数宣言直後の空行を削除することを検討してください

PRの目的にも記載されている通り、定数宣言の直後に不要な空行があります。コードの一貫性のため削除を推奨します。

♻️ 提案される修正
 export const HTTP_STATUS = {
   BAD_REQUEST: 400,
   UNAUTHORIZED: 401,
   FORBIDDEN: 403,
   NOT_FOUND: 404,
 } as const;
-
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const HTTP_STATUS = {
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
} as const;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/github.ts` at line 34, src/lib/github.ts
内の定数宣言の直後にある不要な空行を削除してください。ファイル内のすべての const 宣言(ファイル先頭やモジュールスコープにある const ...; や
const <識別子> = ...;)を探し、定数宣言の直後にある単一の空行を取り除いてコードの一貫性を戻してください。該当箇所は "const"
キーワードを含む宣言を目印に修正してください。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant