Skip to content

Conversation

xixas
Copy link
Contributor

@xixas xixas commented Dec 13, 2024

Updated DTO to keep input file mandatory
Added transform option to validation pipe

API PR Checklist

Pre-requisites

  • I have gone through the Contributing guidelines for Submitting a Pull Request (PR) and ensured that this is not a duplicate PR.
  • I have performed preliminary unit testing.
  • I have updated the required api docs as applicable.
  • I have added/updated test cases to the test suite as applicable

PR Details

PR details have been updated as per the given format (see below)

  • PR title adheres to the format specified in guidelines (e.g., feat: add admin login endpoint)
  • Description has been added
  • Related changes have been added (optional)
  • Screenshots have been added (optional)
  • Query request and response examples have been added (as applicable, in case added or updated)
  • Documentation changes have been listed (as applicable)
  • Test suite output is added (as applicable)
  • Pending actions have been added (optional)
  • Any other additional notes have been added (optional)

Additional Information

  • Appropriate label(s) have been added (ready for review should be added if the PR is ready to be reviewed)
  • Assignee(s) and reviewer(s) have been added (optional)

Description:

  • Updated DTO to keep input file mandatory
  • Added transform option to validation pipe

Related changes:

N/A

Screenshots:

Add any screenshots as required.

Query request and response:

  • Add any query request body, cURL statement and response body for the made change or addition.

Documentation changes:

  • Add a list of changes made to the API documents with brief descriptions.

Test suite output:

  • Add the output of the status of different test cases in the testing suite.

Pending actions:

  • Add list of any pending actions that have or would require to be done in this PR.

Additional notes:

  • Add list of any additional notes you may want to convey in this PR.

Summary by CodeRabbit

  • New Features

    • Enhanced data handling capabilities with automatic transformation of payloads to DTO types.
  • Bug Fixes

    • Updated validation logic to require the inputFile property when creating a summary instance.

Updated DTO to keep input file mandatory
Added transform option to validation pipe
Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Walkthrough

The changes in this pull request involve updates to the global validation pipe configuration in the main.ts file, specifically by adding the transform: true option to the ValidationPipe. This modification enables automatic transformation of payloads into their corresponding DTO types. Additionally, the CreateSummaryDTO class in create-summary.dto.ts has been altered to make the inputFile property required, removing its optional status. These changes affect the validation logic and data handling capabilities of the application.

Changes

File Path Change Summary
apps/api/src/main.ts Updated app.useGlobalPipes(new ValidationPipe()) to app.useGlobalPipes(new ValidationPipe({ transform: true })) to enable automatic transformation of payloads.
apps/api/src/modules/summary/dto/create-summary.dto.ts Changed inputFile?: Promise<FileUpload>; to inputFile: Promise<FileUpload>;, making inputFile a required property in CreateSummaryDTO.

Possibly related PRs

  • feat: add file upload feature using graphql #18: This PR modifies the main.ts file to add middleware for handling file uploads, which is directly related to the changes in the main PR that updates the global validation pipe configuration in the same file.
  • feat: add API integration for uploading file #23: This PR introduces API integration for file uploading, which involves changes to the create-summary.dto.ts file, where the inputFile property is modified. This is relevant as it relates to the handling of file uploads and the validation of the DTOs in the main PR.

Suggested labels

Ready for review

Poem

🐇 In the code where data flows,
A pipe now transforms, as it knows.
Required files, no more to hide,
With DTOs ready, we take pride.
Hopping through changes, oh what a sight,
Our app's now brighter, all feels just right! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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: 1

🧹 Outside diff range and nitpick comments (3)
apps/api/src/modules/summary/dto/create-summary.dto.ts (1)

Line range hint 1-14: Consider adding file validation constraints

While making the file required is good, consider adding additional validation decorators to ensure secure file uploads:

 @Field(() => GraphQLUpload)
+@IsNotEmpty({ message: 'Input file is required' })
+@ValidatePromise()
+@IsObject()
 inputFile: Promise<FileUpload>;

Also consider adding:

  1. File size validation
  2. File type validation
  3. File name sanitization
apps/api/src/main.ts (2)

Line range hint 36-41: Enhance upload middleware error handling

The current error handling in graphqlUploadExpress could be improved to provide more structured errors:

 app.use(graphqlUploadExpress({ maxFileSize: 1000000, maxFiles: 1 }), (err, req, res, next) => {
   if (err) {
-    res.status(500).json({ error: err.message });
+    const status = err.status || 500;
+    res.status(status).json({
+      status: 'error',
+      code: err.code || 'UPLOAD_ERROR',
+      message: err.message,
+      data: null
+    });
   } else {
     next();
   }
 });

Line range hint 23-31: Secure upload directory configuration

The upload directory configuration needs additional security measures:

  1. The current regex for sanitizing path ([^\w\s/]) might still allow potentially dangerous paths
  2. No validation of absolute path to prevent directory traversal
  3. Default fallback path is within project directory which isn't ideal for production

Consider:

 export const uploadDir =
-  configService.get('UPLOAD_FOLDER_PATH')?.replace(/[^\w\s/]/g, '') ??
-  join(process.cwd(), 'uploads');
+  validateUploadPath(configService.get('UPLOAD_FOLDER_PATH')) ??
+  join(process.env.UPLOAD_BASE_DIR || '/var/uploads', 'summaries');

+function validateUploadPath(path: string | undefined): string | undefined {
+  if (!path) return undefined;
+  const normalized = path.replace(/[^a-zA-Z0-9/_-]/g, '');
+  if (normalized.includes('..') || !path.startsWith('/var/uploads')) {
+    throw new Error('Invalid upload path configuration');
+  }
+  return normalized;
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 57f9208 and 042f86a.

📒 Files selected for processing (2)
  • apps/api/src/main.ts (1 hunks)
  • apps/api/src/modules/summary/dto/create-summary.dto.ts (1 hunks)
🔇 Additional comments (1)
apps/api/src/modules/summary/dto/create-summary.dto.ts (1)

14-14: Verify handling of breaking change across the application

Making inputFile required is a breaking change that could affect existing clients. Ensure all GraphQL queries and mutations using this DTO are updated accordingly.

Consider implementing proper error messages in the GraphQL schema to guide clients about the required file upload:

type Mutation {
  createSummary(input: CreateSummaryInput!): Summary!
    @error(code: "FILE_REQUIRED", message: "Input file is required for summary creation")
}
✅ Verification successful

The previous search might have failed because we need to first identify where this DTO is being used. Let's gather more context about its usage patterns in the codebase to verify the impact of making inputFile required.


Breaking change is already properly handled across the application

The verification shows that making inputFile required is safe because:

  1. The GraphQL mutation in the client code already treats the file as required with $file: Upload! type
  2. The service implementation already expects and handles the file with proper null checks
  3. All client implementations (portal, Postman collections, documentation) consistently show the file as a required parameter

The change aligns the DTO with the existing usage patterns in the codebase, making it more type-safe without introducing breaking changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for GraphQL operations using CreateSummaryDTO
rg -l "CreateSummaryDTO" | xargs rg "mutation.*summary.*\{" -A 5

Length of output: 64


Script:

#!/bin/bash
# Let's first find all files containing CreateSummaryDTO
rg -l "CreateSummaryDTO"

# Then search for GraphQL mutations in resolver files
fd resolver | xargs rg "createSummary.*\(" -A 5

# Also search for any test files that might be using this DTO
fd "\.spec\.|\.test\." | xargs rg "CreateSummaryDTO"

Length of output: 1112


Script:

#!/bin/bash
# Let's check the implementation in the service to see how it handles the file
rg -A 10 "createSummary.*\(" "apps/api/src/modules/summary/summary.service.ts"

# Let's also check for any GraphQL schema definitions
fd "\.graphql$|schema\.ts$" | xargs rg "createSummary|CreateSummaryInput"

# And check the actual resolver implementation to see the decorator setup
ast-grep --pattern 'class SummaryResolver {
  $$$
  @Mutation($_)
  createSummary($$$) {
    $$$
  }
  $$$
}'

Length of output: 3548

@osm-vishnukyatannawar osm-vishnukyatannawar merged commit 0f0ae60 into main Feb 7, 2025
6 checks passed
@osm-vishnukyatannawar osm-vishnukyatannawar deleted the bugfix/graph-upload-error-handling branch February 7, 2025 15:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ready for review Ready for review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants