Skip to content

fix: Validations for session api#1467

Merged
sujitaw merged 2 commits intomainfrom
fix/validations_for_session_api
Sep 26, 2025
Merged

fix: Validations for session api#1467
sujitaw merged 2 commits intomainfrom
fix/validations_for_session_api

Conversation

@sujitaw
Copy link
Copy Markdown
Contributor

@sujitaw sujitaw commented Sep 26, 2025

What

  • added separate validation for empty space.

Summary by CodeRabbit

  • Bug Fixes
    • Prevented empty or whitespace-only IDs from being accepted on user session listing and session deletion endpoints.
    • Preserved trimming and UUID validation while adding early empty-string checks for more reliable request handling.
    • Improved error messages for missing parameters: clearer, capitalized messages and a generic fallback when parameter naming is unavailable.

Signed-off-by: sujitaw <sujit.sutar@ayanworks.com>
@sujitaw sujitaw requested a review from shitrerohit September 26, 2025 06:37
@sujitaw sujitaw self-assigned this Sep 26, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Sep 26, 2025

Walkthrough

Introduces EmptyStringParamPipe into AuthzController route parameter validation for userId and sessionId, augmenting the existing TrimStringParamPipe and ParseUUIDPipe chain. Enhances EmptyStringParamPipe error messaging logic in cast.helper.ts without altering successful flow or method signatures.

Changes

Cohort / File(s) Summary
AuthzController param validation
apps/api-gateway/src/authz/authz.controller.ts
Adds EmptyStringParamPipe to @param for userSessions (userId) and deleteSession (sessionId). Maintains TrimStringParamPipe and ParseUUIDPipe. Updates imports to include EmptyStringParamPipe from cast.helper.
Param pipe error handling
libs/common/src/cast.helper.ts
Refines EmptyStringParamPipe.transform error messages: differentiates missing/non-string param name vs. named param; preserves behavior for non-empty strings. No change to normal return path.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant G as API Gateway
  participant AC as AuthzController
  participant P as Param Pipes
  participant H as Handler

  C->>G: HTTP request (userId/sessionId)
  G->>AC: Route match
  AC->>P: Apply EmptyStringParamPipe → TrimStringParamPipe → ParseUUIDPipe
  alt Empty or missing value
    P-->>AC: Throw BadRequestException (message varies)
    AC-->>G: 400 response
    G-->>C: 400 Bad Request
  else Valid UUID
    P-->>AC: Validated param
    AC->>H: Invoke controller method
    H-->>AC: Response
    AC-->>G: 200/204 response
    G-->>C: Success
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • shitrerohit

Poem

A hop, a stop—no empty string slips by,
I twitch my ears at params that lie.
Trim, then parse, with tidy cheer,
UUIDs clear, the path sincere.
Thump-thump—bad requests take flight,
Pipes aligned, all fields made right. 🐇✨

Pre-merge checks and finishing touches

✅ 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 succinctly communicates that the pull request addresses validation issues in the session API endpoints by adding empty‐string checks for session and user IDs, which aligns with the main changes in the code. It uses a common “fix” prefix to indicate intent and directly references the affected area without extraneous detail. While it could be more granular, it accurately captures the primary update.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/validations_for_session_api

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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.

@sonarqubecloud
Copy link
Copy Markdown

Copy link
Copy Markdown

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
libs/common/src/cast.helper.ts (1)

187-195: Guard against undefined/non-string before calling trim to avoid runtime TypeError

value.trim() will throw if the param is missing or not a string. Add a type/emptiness guard before trimming and reuse the same required message logic to keep responses consistent.

Apply this diff:

   // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type
   transform(value: string) {
-    const trimmedValue = value.trim();
-
-    if (!trimmedValue) {
-      if (!this.paramName || 'string' !== typeof this.paramName) {
-        throw new BadRequestException(`Parameter is required and cannot be empty`);
-      }
-      throw new BadRequestException(`${this.paramName[0].toUpperCase() + this.paramName.slice(1)} is required`);
-    }
+    const hasName = 'string' === typeof this.paramName && this.paramName.trim().length > 0;
+    const requiredMsg = hasName
+      ? `${this.paramName.trim()[0].toUpperCase() + this.paramName.trim().slice(1)} is required`
+      : 'Parameter is required and cannot be empty';
+
+    if (value === undefined || value === null || 'string' !== typeof value) {
+      throw new BadRequestException(requiredMsg);
+    }
+
+    const trimmedValue = value.trim();
+    if (!trimmedValue) {
+      throw new BadRequestException(requiredMsg);
+    }
 
     return plainToClass(String, trimmedValue);
   }
🧹 Nitpick comments (2)
apps/api-gateway/src/authz/authz.controller.ts (2)

383-392: Good addition of EmptyStringParamPipe before UUID parsing

Placing EmptyStringParamPipe.forParam('userId') before trim and ParseUUIDPipe ensures clear “required” errors for blank/space-only inputs.

You can drop new TrimStringParamPipe() here since EmptyStringParamPipe already returns a trimmed string.


426-435: Consistent validation for sessionId

Same pattern applied to sessionId is correct and improves error clarity.

new TrimStringParamPipe() is redundant after EmptyStringParamPipe; consider removing to simplify the chain.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 72bfb3e and cc85b35.

📒 Files selected for processing (2)
  • apps/api-gateway/src/authz/authz.controller.ts (3 hunks)
  • libs/common/src/cast.helper.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/api-gateway/src/authz/authz.controller.ts (1)
libs/common/src/cast.helper.ts (1)
  • EmptyStringParamPipe (175-199)
🔇 Additional comments (1)
apps/api-gateway/src/authz/authz.controller.ts (1)

57-57: Import looks correct

Importing EmptyStringParamPipe alongside TrimStringParamPipe from common is consistent with usage below.

@sujitaw sujitaw merged commit 2ee1a3b into main Sep 26, 2025
8 checks passed
ankita-p17 pushed a commit that referenced this pull request Sep 30, 2025
Signed-off-by: sujitaw <sujit.sutar@ayanworks.com>
Signed-off-by: Ankita Patidar <ankita.patidar@ayanworks.com>
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.

2 participants