Skip to content

🧹 Refactor duplicated response parsing logic#20

Open
instax-dutta wants to merge 1 commit into
mainfrom
refactor-response-parsing-2327660267229171752
Open

🧹 Refactor duplicated response parsing logic#20
instax-dutta wants to merge 1 commit into
mainfrom
refactor-response-parsing-2327660267229171752

Conversation

@instax-dutta

@instax-dutta instax-dutta commented Mar 22, 2026

Copy link
Copy Markdown
Owner

🎯 What: The code health issue addressed was duplicated response parsing logic across multiple client-side components. I extracted this pattern into a new handleResponse helper function in src/lib/utils.ts.

💡 Why: This improves maintainability by centralizing the logic for status checking, content-type verification, and error extraction from fetch responses. It prevents drift and makes the calling code cleaner and easier to read.

Verification:

  • Created a unit test suite for handleResponse using the native node:test runner.
  • Verified that handleResponse correctly parses JSON on success and throws descriptive errors on failure.
  • Confirmed syntax for all modified files using node --experimental-strip-types --check.
  • Performed a code review to ensure the refactor is safe and consistent with the codebase patterns.

Result: Reduced code duplication and established a consistent pattern for client-side API interactions.


PR created automatically by Jules for task 2327660267229171752 started by @instax-dutta

Summary by CodeRabbit

  • Refactor
    • Streamlined error handling and response parsing across the application for improved code consistency and maintainability.

- Extract manual fetch response checking and JSON parsing into `handleResponse` in `src/lib/utils.ts`.
- Update `src/app/revoke/page.tsx` to use the new utility in `handleRevoke` and `handleRotate`.
- Update `src/components/PasteEditor.tsx` to use the new utility in `handleCreate`.
- Use TypeScript generics to maintain type safety for returned data.
- Improve error handling with robust JSON parsing and fallback messages.

Co-authored-by: instax-dutta <54683866+instax-dutta@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 Mar 22, 2026

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
binify Ready Ready Preview, Comment Mar 22, 2026 9:30am

@coderabbitai

coderabbitai Bot commented Mar 22, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

A refactoring that extracts shared response parsing and error handling logic into a new utility function handleResponse in src/lib/utils.ts, then updates two existing components to delegate their manual response processing to this utility instead of duplicating the logic.

Changes

Cohort / File(s) Summary
Response Handling Utility
src/lib/utils.ts
Added new exported async function handleResponse<T>() that inspects content-type, conditionally parses JSON, throws errors with data.error fallback when response.ok is false, and returns typed payload on success.
Component Refactoring
src/app/revoke/page.tsx, src/components/PasteEditor.tsx
Replaced manual response parsing and error checking with calls to handleResponse() utility. Both components now delegate parsing and error handling to the shared utility instead of inline logic.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

Bunny hops through code so clean,
Pulling out logic caught between,
One small function, reused with care,
DRY principles floating through the air! 🐰✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title describes the main refactoring work—extracting duplicated response parsing logic into a shared utility—which directly matches the core objective and changes shown in the summary.

✏️ 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 refactor-response-parsing-2327660267229171752

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.

Tip

Migrating from UI to YAML configuration.

Use the @coderabbitai configuration command in a PR comment to get a dump of all your UI settings in YAML format. You can then edit this YAML file and upload it to the root of your repository to configure CodeRabbit programmatically.

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/lib/utils.ts`:
- Around line 15-19: The code around the response.json() try/catch swallows JSON
parse errors (in the block where data = await response.json()), and later
returns an empty object cast to T, which hides parsing failures; update the
logic in the function handling the fetch/response (reference variables:
response, data) to surface JSON parse errors instead of swallowing them — if
response.ok but response.json() throws, capture the parsing error and throw a
new Error (or reject) that includes the original error message and response
metadata (status/headers/body text) so callers see a clear parsing/fetch failure
rather than receiving an empty {} cast to T.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e2d88a6f-e5a3-4de0-a630-10b444e2482c

📥 Commits

Reviewing files that changed from the base of the PR and between 6c75fd8 and b7c08f1.

📒 Files selected for processing (3)
  • src/app/revoke/page.tsx
  • src/components/PasteEditor.tsx
  • src/lib/utils.ts

Comment thread src/lib/utils.ts
Comment on lines +15 to +19
try {
data = await response.json();
} catch (e) {
// If JSON parsing fails despite the content-type, we'll stick with the default error
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Do not swallow JSON parse failures on successful responses.

Line 15-19 currently ignores parse errors and Line 26 returns an empty object cast to T. That can surface as downstream runtime errors (e.g., missing required fields) instead of a clear fetch/parsing failure at the source.

Proposed fix
 export async function handleResponse<T>(response: Response, defaultErrorMessage: string): Promise<T> {
-    let data: any = {};
-    const contentType = response.headers.get('content-type');
-    if (contentType && contentType.includes('application/json')) {
+    let data: any = {};
+    const contentType = response.headers.get('content-type');
+    const isJson = Boolean(contentType && contentType.includes('application/json'));
+
+    if (isJson) {
         try {
             data = await response.json();
-        } catch (e) {
-            // If JSON parsing fails despite the content-type, we'll stick with the default error
+        } catch {
+            if (response.ok) {
+                throw new Error(defaultErrorMessage);
+            }
         }
     }
 
     if (!response.ok) {
         throw new Error(data.error || defaultErrorMessage);
     }
 
+    if (!isJson) {
+        throw new Error(defaultErrorMessage);
+    }
+
     return data as T;
 }

Also applies to: 26-26

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/utils.ts` around lines 15 - 19, The code around the response.json()
try/catch swallows JSON parse errors (in the block where data = await
response.json()), and later returns an empty object cast to T, which hides
parsing failures; update the logic in the function handling the fetch/response
(reference variables: response, data) to surface JSON parse errors instead of
swallowing them — if response.ok but response.json() throws, capture the parsing
error and throw a new Error (or reject) that includes the original error message
and response metadata (status/headers/body text) so callers see a clear
parsing/fetch failure rather than receiving an empty {} cast to T.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant