Skip to content

Standarized the API Response in Package-Middleware#270

Merged
yash-pouranik merged 2 commits into
geturbackend:mainfrom
Ayush4958:pr-packages-middleware
Jun 5, 2026
Merged

Standarized the API Response in Package-Middleware#270
yash-pouranik merged 2 commits into
geturbackend:mainfrom
Ayush4958:pr-packages-middleware

Conversation

@Ayush4958
Copy link
Copy Markdown
Contributor

@Ayush4958 Ayush4958 commented Jun 4, 2026

🚀 Pull Request Description

I had added AppError and AppResponse Utility to entire backend's middleware of pcakage/common which provide a standard way to operate. Migrated raw JSON response with standard utility.

Fixes #237

🛠️ Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📝 Documentation update
  • 🎨 UI/UX improvement (Frontend only)
  • ⚙️ Refactor / Chore

🧪 Testing & Validation

Backend Verification:

  • I have run npm test in the backend/ directory and all tests passed.
  • I have verified the API endpoints using Postman/Thunder Client.
  • New unit tests have been added (if applicable).

Frontend Verification:

  • I have run npm run lint in the frontend/ directory.
  • Verified the UI changes on different screen sizes (Responsive).
  • Checked for any console errors in the browser dev tools.

📸 Screenshots / Recordings (Optional)

✅ Checklist

  • My code follows the code style of this project.
  • [xI have performed a self-review of my code.
  • I have commented my code, particularly in hard-to-understand areas.
  • My changes generate no new warnings or errors.
  • I have updated the documentation (README/Docs) accordingly.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added standardized API response handling for successful requests.
    • Added cleanup utility for email queue worker management.
  • Bug Fixes

    • Improved email address formatting to properly handle pre-formatted sender strings.
  • Improvements

    • Enhanced error response messages with better structured error information.
    • Streamlined error handling across middleware layers for consistency.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 4, 2026

Review Change Stack

Warning

Review limit reached

@Ayush4958, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 48 minutes and 25 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, 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 include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 240eb4d2-cc69-4b47-a582-c0d63e4b41a2

📥 Commits

Reviewing files that changed from the base of the PR and between 52dd2ab and f09d33b.

📒 Files selected for processing (2)
  • packages/common/src/middleware/loadProjectForAdmin.js
  • packages/common/src/middleware/standardizeApiResponse.js
📝 Walkthrough

Walkthrough

This PR standardizes error handling and response schemas across the common package by introducing ApiResponse for success responses, enhancing AppError with flexible error metadata, converting middlewares to centralized error propagation via next(), improving response field extraction, and adding queue cleanup and email formatting improvements.

Changes

Standardized Error and Response Handling

Layer / File(s) Summary
Success Response and Error Class Foundations
packages/common/src/utils/ApiResponse.js, packages/common/src/utils/AppError.js, packages/common/src/index.js
ApiResponse class standardizes successful responses with data and message fields and a send() method; AppError constructor now accepts an optional error parameter for custom error titles; both are exported through the package entrypoint.
Middleware Conversion to Centralized Error Flow
packages/common/src/middleware/checkAuthEnabled.js, packages/common/src/middleware/loadProjectForAdmin.js, packages/common/src/middleware/verifyEmail.js
All three middlewares now use next(new AppError(...)) to forward validation failures (403 for auth disabled/users missing, 422 for schema validation, 400/404/500 for project errors, 401 for unverified email) instead of writing HTTP responses directly.
Standardized Error Field Extraction
packages/common/src/middleware/standardizeApiResponse.js
Error response payloads now extract errorTitle from body.error and errorMessage from body.message when present, falling back to defaults and supporting cases where only one field is provided.
Queue Worker Cleanup and Email Formatting
packages/common/src/queues/publicEmailQueue.js, packages/common/src/utils/emailService.js
resetPublicEmailWorker async function safely shuts down the BullMQ worker and nulls the reference; formatFromAddress now recognizes and preserves pre-formatted "Name <email@domain.com>" sender addresses.

Sequence Diagram

sequenceDiagram
  participant Middleware as checkAuthEnabled/<br/>loadProjectForAdmin/<br/>verifyEmail
  participant ExpressNext as Express next()
  participant ErrorHandler as Error Handler<br/>Middleware
  participant standardize as standardizeApiResponse
  participant Client
  Middleware->>ExpressNext: next(new AppError(code, message, error))
  ExpressNext->>ErrorHandler: pass AppError instance
  ErrorHandler->>standardize: response with body={error, message}
  standardize->>standardize: extract errorTitle, errorMessage from body
  standardize->>Client: send {success: false, error, message}
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • geturbackend/urBackend#66: Both PRs directly touch packages/common/src/middleware/standardizeApiResponse.js, with PR #66 introducing/registering the middleware and this PR refining the error payload extraction logic.
  • geturbackend/urBackend#157: Both PRs modify packages/common/src/queues/publicEmailQueue.js; PR #157 defines worker behavior while this PR adds the resetPublicEmailWorker cleanup function around the shared worker instance.
  • geturbackend/urBackend#140: Both PRs align API error/response handling around shared AppError and standardized { success, data, message } response flows, with complementary changes to analytics controller and common middleware.

Suggested labels

GSSOC'26, level:intermediate, quality:clean, type:refactor

Suggested reviewers

  • yash-pouranik

Poem

🐰 With errors now centered and responses so clear,
The middleware flows through next() without fear.
ApiResponse blooms, AppError takes flight,
Standardized schemas make everything right! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR addresses issue #237 by creating AppError and AppResponse utilities and migrating middleware to use them for standardized responses. However, specific middleware mentioned in #237 (authorizeReadOperation.js, verifyApiKey.js) are not visibly updated in the changeset. Verify that all middleware mentioned in issue #237 (authorizeReadOperation.js, verifyApiKey.js) have been updated to use the new standardized response format, or clarify if they will be addressed in a follow-up PR.
Out of Scope Changes check ⚠️ Warning While most changes align with standardizing responses, modifications to emailService.js (formatFromAddress function) and resetPublicEmailWorker addition appear tangential to the core objective of standardizing error response schemas across middleware. Consider separating unrelated changes (emailService.js formatting and publicEmailQueue worker reset) into separate PRs to maintain focus on the standardization objective outlined in issue #237.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title references 'Standarized the API Response in Package-Middleware' which is partially related to the changeset's main objective of standardizing error responses, but it contains a typo ('Standarized' should be 'Standardized') and is somewhat vague about the scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/common/src/queues/publicEmailQueue.js (1)

15-29: ⚡ Quick win

Consider logging cleanup errors in non-test environments.

The function silently swallows all errors during cleanup, which could make debugging production shutdown issues difficult. While best-effort cleanup is appropriate here, logging errors would help diagnose rare but problematic worker shutdown failures.

📝 Suggested enhancement
     } catch (_) {
         // Best-effort cleanup for test/runtime shutdown paths.
+        if (process.env.NODE_ENV !== 'test') {
+            console.error('[Queue] Worker cleanup error:', _);
+        }
     } finally {
🤖 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 `@packages/common/src/queues/publicEmailQueue.js` around lines 15 - 29, The
resetPublicEmailWorker function currently swallows all errors during cleanup;
change the catch to capture the thrown error (e.g., catch (err)) and log it in
non-test environments so production shutdown failures are visible. Update
resetPublicEmailWorker to check process.env.NODE_ENV !== 'test' (or similar env
check) and emit the error via your project logger (prefer logger.error if
available, otherwise console.error) including context like
"resetPublicEmailWorker cleanup error" and the error object; still keep the
best-effort behavior and ensure worker is nulled in finally.
🤖 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 `@packages/common/src/middleware/loadProjectForAdmin.js`:
- Line 18: In the loadProjectForAdmin middleware replace forwarding raw
err.message into the 500 AppError response: do not pass err.message into new
AppError(500, ...); instead log the full error server-side (e.g.,
logger.error(err) or console.error(err)) and call next(new AppError(500,
"Internal Server Error")) so the client only receives a generic message; update
the callsite where next(new AppError(500, err.message, "Internal Server Error"))
is used to reference AppError with the generic client message and preserve raw
err in server logs.

In `@packages/common/src/middleware/standardizeApiResponse.js`:
- Around line 75-77: The branch that sets errorMessage from body.error must
ensure a string value; update the logic around the body.error check (the branch
that currently sets errorTitle = 'Error' and errorMessage = body.error) to guard
and coerce body.error to a string: if body.error is already a string use it,
else try String(body.error) or JSON.stringify(body.error) with a safe fallback
(e.g., a generic message) so errorMessage always satisfies the response schema;
adjust the code in the same scope where errorTitle/errorMessage are assigned
(the standardize response branch handling body.error and body.message).

---

Nitpick comments:
In `@packages/common/src/queues/publicEmailQueue.js`:
- Around line 15-29: The resetPublicEmailWorker function currently swallows all
errors during cleanup; change the catch to capture the thrown error (e.g., catch
(err)) and log it in non-test environments so production shutdown failures are
visible. Update resetPublicEmailWorker to check process.env.NODE_ENV !== 'test'
(or similar env check) and emit the error via your project logger (prefer
logger.error if available, otherwise console.error) including context like
"resetPublicEmailWorker cleanup error" and the error object; still keep the
best-effort behavior and ensure worker is nulled in finally.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: e48cc0d1-d579-4ad4-b414-c9944451fc86

📥 Commits

Reviewing files that changed from the base of the PR and between 190b325 and 52dd2ab.

📒 Files selected for processing (9)
  • packages/common/src/index.js
  • packages/common/src/middleware/checkAuthEnabled.js
  • packages/common/src/middleware/loadProjectForAdmin.js
  • packages/common/src/middleware/standardizeApiResponse.js
  • packages/common/src/middleware/verifyEmail.js
  • packages/common/src/queues/publicEmailQueue.js
  • packages/common/src/utils/ApiResponse.js
  • packages/common/src/utils/AppError.js
  • packages/common/src/utils/emailService.js

Comment thread packages/common/src/middleware/loadProjectForAdmin.js Outdated
Comment thread packages/common/src/middleware/standardizeApiResponse.js Outdated
@Ayush4958
Copy link
Copy Markdown
Contributor Author

@yash-pouranik ,
I had done all changes requested from code Rabbit and
This PR also passes all CI test So ,
Its ready to merge

Copy link
Copy Markdown
Collaborator

@yash-pouranik yash-pouranik left a comment

Choose a reason for hiding this comment

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

Thank you for the PR
Everything look perfiect

@yash-pouranik yash-pouranik merged commit de448d4 into geturbackend:main Jun 5, 2026
8 checks passed
@yash-pouranik
Copy link
Copy Markdown
Collaborator

please remember one thing that, UI is ok to handle those New responses.
@Ayush4958

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Standardize Error Response Schemas Across All Middlewares

2 participants