Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created Feedback Submission System #65

Merged
merged 7 commits into from
Oct 5, 2024

Conversation

samar12-rad
Copy link
Contributor

@samar12-rad samar12-rad commented Oct 4, 2024

This PR integrates the frontend feedback form with the backend, introduces a feedback controller, and sets up routes for future handling of feedback submissions, for the issue #33 .

Changes Made:

Feedback Form Backend Integration:
Connected the existing frontend feedback form to the backend system, enabling users to submit their feedback.

Database Model for Feedback:
Created a database model to store feedback, capturing fields such as user comments, email, and user name.

Feedback Routes:
Added backend routes, including a POST route (/submit-feedback) to handle feedback submissions and store them in the database.
Additional routes were created for future management and retrieval of feedback data.

Feedback Controller:
Implemented a feedback controller to manage logic for handling feedback submissions and future feedback-related functionality.

Response Handling:
Users receive success or failure responses based on whether their feedback was submitted successfully.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a feedback submission feature, allowing users to provide feedback through a dedicated form.
    • Added a welcome message and API versioning to the feedback endpoint.
    • Implemented a new feedback creation API endpoint.
  • Improvements

    • Enhanced the feedback form to handle submissions asynchronously with improved error handling and user feedback during submission.
    • Updated the application to ignore environment configuration files in version control.
  • Bug Fixes

    • Resolved issues related to feedback submission by validating input data.

Copy link

vercel bot commented Oct 4, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
play-cafe ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 5, 2024 3:26am
play-cafe-backen ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 5, 2024 3:26am

Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

Warning

Rate limit exceeded

@RamakrushnaBiswal has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 44 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, 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 have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between b42bd8d and d2a7020.

Walkthrough

The changes in this pull request involve updates to the feedback functionality within the application. Key modifications include the removal of the MONGO_URI environment variable, the addition of a feedback creation endpoint, and the introduction of a Mongoose model for feedback. A new router has been set up for handling feedback-related requests, and the frontend feedback form component has been enhanced to support asynchronous submission and error handling.

Changes

File Change Summary
backend/.env Removed MONGO_URI environment variable.
backend/.gitignore Added .env to the ignore list.
backend/config/api.info.js Introduced a module exporting metadata for a feedback API, including a createFeedback endpoint.
backend/controller/feedback.controller.js Added createFeedback function for feedback submission, including validation using zod.
backend/models/feedback.model.js Introduced feedback.model.js defining the feedbackSchema and the Feedback model for MongoDB interactions.
backend/routes/feedbackRouter.js Created feedbackRouter.js with POST /create endpoint for feedback submissions and a GET endpoint for API information.
backend/routes/index.js Integrated feedback routes by adding middleware for feedbackRouter.
frontend/.gitignore Added multiple environment configuration files to the ignore list.
frontend/src/components/ui/FeedbackForm.jsx Modified handleSubmit to be asynchronous, implementing fetch for submitting feedback with error handling.
backend/package.json Added validator package as a dependency.

Possibly related PRs

  • Created Feedback Submission System  #65: The changes in this PR involve the removal of the MONGO_URI variable from the backend/.env file, which directly relates to the main PR's change of removing the same variable. Additionally, both PRs modify the .gitignore file to include the .env file, indicating a shared focus on environment variable management.

Poem

🐰 In the garden where feedback blooms,
A new path opens, dispelling glooms.
With forms that flutter, async delight,
We gather voices, shining bright.
From MONGO_URI to routes anew,
Together we hop, creating for you! 🌼


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 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

github-actions bot commented Oct 4, 2024

Thank you for submitting your pull request! 🙌 We'll review it as soon as possible. In the meantime, please ensure that your changes align with our CONTRIBUTING.md. If there are any specific instructions or feedback regarding your PR, we'll provide them here. Thanks again for your contribution! 😊

Copy link

gitguardian bot commented Oct 4, 2024

⚠️ GitGuardian has uncovered 3 secrets following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

Since your pull request originates from a forked repository, GitGuardian is not able to associate the secrets uncovered with secret incidents on your GitGuardian dashboard.
Skipping this check run and merging your pull request will create secret incidents on your GitGuardian dashboard.

🔎 Detected hardcoded secrets in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
- - MongoDB Credentials ed67389 backend/.env View secret
- - MongoDB Credentials 6494bc9 backend/.env View secret
14023932 Triggered MongoDB Credentials 6494bc9 backend/.env View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secrets safely. Learn here the best practices.
  3. Revoke and rotate these secrets.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

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

🧹 Outside diff range and nitpick comments (7)
backend/routes/index.js (2)

Line range hint 9-16: Update root endpoint information to include the new feedback endpoint.

The root endpoint response doesn't reflect the newly added feedback endpoint. Consider updating the endpoints object in the response to include the feedback endpoint for completeness and to assist API users.

Here's a suggested update:

 endpoints: {
   Reservation: "/reservation",
+  Feedback: "/feedback",
 },

Line range hint 1-2: Remove unused Reservation model import.

The Reservation model is imported but not used in this file. Consider removing this unused import to keep the code clean and avoid potential confusion.

Apply this diff to remove the unused import:

 const express = require("express");
-const Reservation = require("../models/reservation.model");
backend/routes/feedbackRouter.js (1)

1-3: Remove unused import

The Feedback model is imported but not used in this file. Consider removing this import to keep the code clean and avoid potential confusion.

Apply this diff to remove the unused import:

const express = require("express");
-const Feedback = require("../models/feedback.model");
const createFeedback = require("../controller/feedback.controller");
backend/controller/feedback.controller.js (4)

11-23: LGTM! Consider adding input sanitization.

The validation logic and error handling are well-implemented. Good job on using console.error for logging validation errors, which will be helpful for debugging.

Consider adding input sanitization before validation to prevent potential XSS attacks. You could use a library like xss to sanitize the input:

const xss = require('xss');

// Inside the createFeedback function, before validation
const sanitizedBody = {
  name: xss(req.body.name),
  email: xss(req.body.email),
  feedback: xss(req.body.feedback),
};

const validationResult = feedbackSchema.safeParse(sanitizedBody);

This ensures that any malicious scripts in the input are neutralized before processing.


24-30: LGTM! Consider adding specific error handling for database operations.

The feedback creation and success response are well-implemented. Good job on using the correct 201 status code for resource creation and including the created feedback data in the response.

Consider adding specific error handling for database operations. This can help distinguish between different types of errors (e.g., validation errors vs. database errors) and provide more informative error messages. For example:

try {
  const feedback = await Feedback.create(validationResult.data);
  // ... success response ...
} catch (error) {
  if (error.name === 'ValidationError') {
    return res.status(400).json({
      success: false,
      message: "Database validation failed",
      errors: error.errors,
    });
  }
  // ... handle other specific error types ...
  throw error; // rethrow unhandled errors
}

This approach allows for more granular error handling and can provide more helpful responses to the client.


31-47: LGTM! Consider enhancing error logging and moving the API example to documentation.

The general error handling and module export are well-implemented.

  1. Enhance error logging:
    Instead of just logging the error message, consider logging the full error stack trace for better debugging:

    console.error("Error creating feedback:", error.stack);
  2. API documentation:
    The dummy API call example is helpful but could be moved to a separate documentation file or added as a JSDoc comment above the createFeedback function. This keeps the actual code clean while still providing useful information for developers.

    /**
     * Creates a new feedback entry
     * @param {Object} req - The request object
     * @param {Object} req.body - The request body
     * @param {string} req.body.name - The name of the user
     * @param {string} req.body.email - The email of the user
     * @param {string} req.body.feedback - The feedback text
     * @param {Object} res - The response object
     * @returns {Promise<void>}
     * 
     * @example
     * // API call example
     * // POST /api/feedback
     * // {
     * //     "name": "John Doe",
     * //     "email": "john@example.com",
     * //     "feedback": "This is a dummy feedback"
     * // }
     */
    async function createFeedback(req, res) {
      // ... function implementation ...
    }

This approach improves code readability while maintaining helpful documentation.


1-47: Overall, good implementation with room for enhancements.

The feedback controller successfully implements the core functionality described in the PR objectives. It handles feedback submission, validation, and storage effectively. The code is well-structured and follows good practices.

To further improve the implementation, consider the following summary of suggestions:

  1. Enhance the feedback schema with more specific validation rules.
  2. Add input sanitization to prevent XSS attacks.
  3. Implement more granular error handling, especially for database operations.
  4. Improve error logging by including stack traces.
  5. Move the API call example to JSDoc comments or separate documentation.

These enhancements will make the code more robust, secure, and developer-friendly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 57eb294 and 6494bc9.

📒 Files selected for processing (6)
  • backend/.env (1 hunks)
  • backend/controller/feedback.controller.js (1 hunks)
  • backend/models/feedback.model.js (1 hunks)
  • backend/routes/feedbackRouter.js (1 hunks)
  • backend/routes/index.js (1 hunks)
  • frontend/src/components/ui/FeedbackForm.jsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • backend/.env
🔇 Additional comments (8)
backend/models/feedback.model.js (3)

1-2: LGTM: Proper import and setup.

The import statements and initial setup are correct and follow best practices for using Mongoose.


19-21: LGTM: Proper model creation and export.

The Mongoose model 'Feedback' is correctly created and exported, following standard conventions.


1-21: Overall assessment: Good implementation with room for enhancement.

The feedback.model.js file successfully introduces a Mongoose schema for the feedback submission system, aligning well with the PR objectives. The basic structure is sound, including all necessary fields for name, email, and feedback.

While the current implementation is functional, the suggested improvements for data validation, security, and additional features like timestamps will significantly enhance the robustness and reliability of the feedback system.

Great job on laying the foundation for the feedback submission system!

backend/routes/index.js (1)

6-6: LGTM! New feedback route successfully added.

The new feedback route has been correctly integrated into the main router. This aligns with the PR objective of implementing a feedback submission system.

backend/routes/feedbackRouter.js (3)

5-7: LGTM: Router and POST route setup

The Express router is correctly initialized, and the POST route for creating feedback is properly defined using the imported createFeedback controller.


20-20: LGTM: Router export

The router is correctly exported, allowing it to be imported and used in other parts of the application.


1-20: Overall assessment: Good foundation with room for improvement

The feedback router is well-structured and provides the necessary endpoints for creating feedback and retrieving API information. Consider implementing the suggested improvements for better code organization, maintainability, and robustness.

To ensure the endpoints are working as expected, it's recommended to add integration tests.

Here's a script to verify the endpoints:

Make sure to replace http://localhost:3000 with the actual server URL and port if different.

frontend/src/components/ui/FeedbackForm.jsx (1)

22-37: LGTM: Async function and fetch implementation.

The overall implementation of the asynchronous function and the fetch call for submitting feedback is correct and follows good practices.

Great job on:

  1. Using async/await for handling the asynchronous fetch call.
  2. Properly stringifying the body of the request.
  3. Checking the response status before proceeding.
  4. Maintaining the existing success handling logic.

backend/models/feedback.model.js Outdated Show resolved Hide resolved
@@ -3,6 +3,7 @@ const Reservation = require("../models/reservation.model");

const router = express.Router();

router.use("/feedback", require("./feedbackRouter"));
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling when requiring feedbackRouter.

To improve robustness, consider wrapping the require statement in a try-catch block. This will help gracefully handle any potential issues that might occur when loading the feedbackRouter module.

Here's a suggested implementation:

let feedbackRouter;
try {
  feedbackRouter = require("./feedbackRouter");
} catch (error) {
  console.error("Error loading feedbackRouter:", error);
  feedbackRouter = (req, res, next) => {
    res.status(500).json({ error: "Feedback functionality is currently unavailable" });
  };
}
router.use("/feedback", feedbackRouter);

backend/routes/feedbackRouter.js Outdated Show resolved Hide resolved
backend/controller/feedback.controller.js Outdated Show resolved Hide resolved
e.preventDefault();
console.log(`Name: ${name}, Email: ${email}, Feedback: ${feedback}`);
const response = await fetch("http://localhost:3000/api/feedback/create", {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use environment variables for API endpoint.

The API endpoint is currently hardcoded, which may cause issues when deploying to different environments (e.g., staging, production).

Consider using environment variables to manage the API URL. For example:

const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:3000';
const response = await fetch(`${API_URL}/api/feedback/create`, {
  // ... rest of the code
});

Make sure to set up the appropriate environment variables in your deployment process.

frontend/src/components/ui/FeedbackForm.jsx Outdated Show resolved Hide resolved
frontend/src/components/ui/FeedbackForm.jsx Outdated Show resolved Hide resolved
@RamakrushnaBiswal
Copy link
Owner

resolve @coderabit suggestions

@samar12-rad
Copy link
Contributor Author

@GitGuardian scan

@samar12-rad
Copy link
Contributor Author

@RamakrushnaBiswal , performed code rabbit changes, removed risks created by git guardian

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: 8

🧹 Outside diff range and nitpick comments (3)
backend/config/api.info.js (2)

1-3: LGTM! Consider updating the documentation URL.

The overall structure of the API info object is clear and well-organized. It follows good practices by including a welcome message, version number, and link to documentation.

Please update the documentation URL on line 15 with the actual documentation link when it becomes available, replacing the placeholder "https://api-docs-url.com".

Also applies to: 15-16


1-16: Consider expanding the API info for more comprehensive documentation.

The current implementation provides a good foundation for API documentation. To make it more robust and useful for API consumers, consider the following suggestions for future improvements:

  1. Add descriptions for each endpoint to explain their purpose.
  2. Include information about expected response formats and status codes.
  3. Define possible error responses and their meanings.
  4. As the API grows, add new endpoints to this configuration file.
  5. Consider adding rate limiting information if applicable.
  6. Include any authentication requirements for the API.

Example of how you might expand the endpoint definition:

createFeedback: {
  path: "/feedback",
  method: "POST",
  description: "Submit user feedback",
  parameters: {
    name: { type: "string", required: true, description: "User's name" },
    email: { type: "string", required: true, description: "User's email" },
    message: { type: "string", required: true, description: "Feedback message" },
  },
  responses: {
  },
}

These suggestions will help create a more comprehensive API documentation, improving the developer experience for those consuming your API.

backend/controller/feedback.controller.js (1)

42-47: Consider removing or relocating the dummy API call example.

While example data can be helpful during development, it's generally not recommended to keep such comments in production code. This information would be more valuable if moved to documentation or included in unit tests.

Consider one of the following options:

  1. Remove the commented-out example entirely if it's no longer needed.
  2. Move this example to a separate documentation file or README.
  3. Create a unit test using this data to ensure the API behaves correctly.

This will help keep the main code file clean and focused on implementation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6494bc9 and ed67389.

📒 Files selected for processing (9)
  • backend/.env (0 hunks)
  • backend/.gitignore (1 hunks)
  • backend/config/api.info.js (1 hunks)
  • backend/controller/feedback.controller.js (1 hunks)
  • backend/models/feedback.model.js (1 hunks)
  • backend/routes/feedbackRouter.js (1 hunks)
  • backend/routes/index.js (1 hunks)
  • frontend/.gitignore (1 hunks)
  • frontend/src/components/ui/FeedbackForm.jsx (3 hunks)
💤 Files with no reviewable changes (1)
  • backend/.env
✅ Files skipped from review due to trivial changes (2)
  • backend/.gitignore
  • frontend/.gitignore
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/routes/feedbackRouter.js
  • backend/routes/index.js
🔇 Additional comments (5)
backend/models/feedback.model.js (3)

39-39: Model creation looks good.

The Feedback model is correctly created using the defined schema.


41-41: Module export is correct.

The Feedback model is properly exported, making it available for use in other parts of the application.


1-41: Overall, excellent implementation of the Feedback model.

This implementation aligns well with the PR objectives of creating a feedback submission system. The model includes all necessary fields (name, email, feedback, createdAt) with proper validation and constraints. The use of Mongoose schema features like maxlength, match, and timestamps enhances data integrity and provides useful metadata.

To fully complete the implementation:

  1. Consider adding input sanitization as suggested earlier.
  2. Ensure that this model is properly integrated with the backend routes, especially the POST route at /submit-feedback mentioned in the PR objectives.
  3. Verify that the feedback controller correctly utilizes this model for managing feedback submissions.

Great job on implementing a robust foundation for the feedback system!

backend/controller/feedback.controller.js (2)

1-2: LGTM: Imports are appropriate.

The imports for Zod and the Feedback model are correctly implemented and suitable for the file's functionality.


4-9: Great job implementing the suggested schema improvements!

The feedback schema now includes more robust validation rules:

  1. The name field has appropriate length constraints (2-100 characters).
  2. The email field uses Zod's built-in email validation.
  3. The feedback field has a minimum length of 10 characters to ensure meaningful feedback.

These improvements will help ensure more meaningful and valid data is submitted.

backend/config/api.info.js Outdated Show resolved Hide resolved
backend/models/feedback.model.js Show resolved Hide resolved
backend/controller/feedback.controller.js Outdated Show resolved Hide resolved
backend/controller/feedback.controller.js Show resolved Hide resolved
frontend/src/components/ui/FeedbackForm.jsx Outdated Show resolved Hide resolved
frontend/src/components/ui/FeedbackForm.jsx Outdated Show resolved Hide resolved
frontend/src/components/ui/FeedbackForm.jsx Outdated Show resolved Hide resolved
frontend/src/components/ui/FeedbackForm.jsx Outdated Show resolved Hide resolved
@samar12-rad
Copy link
Contributor Author

samar12-rad commented Oct 4, 2024

As the code rabbit is suggesting to use a library for logging errors, such as Logger, but there is no such library pressent neither in forntend or backend, can i create an issue to imcorporate the error of whole backend with logger library?

@RamakrushnaBiswal
Copy link
Owner

ok then @samar12-rad go for it

@samar12-rad
Copy link
Contributor Author

@RamakrushnaBiswal . i create the issue. Also, is this PR completed?

@RamakrushnaBiswal
Copy link
Owner

resolve the conflicts please @samar12-rad

Copy link

vercel bot commented Oct 4, 2024

@samar12-rad is attempting to deploy a commit to the bunty's projects Team on Vercel.

A member of the Team first needs to authorize it.

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

🧹 Outside diff range and nitpick comments (3)
backend/models/feedback.model.js (1)

39-57: Good implementation of input sanitization!

The pre-save hook effectively sanitizes the name and feedback fields to prevent XSS attacks. This addresses the previous suggestion for input sanitization.

Consider the following minor improvements:

  1. As mentioned in the comment, replace this basic sanitization with a robust library like DOMPurify for production use.
  2. You might want to sanitize the email field as well, although it's less critical since email addresses are typically not rendered as HTML.

Example of using DOMPurify (you'll need to install it first):

const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');

const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);

feedbackSchema.pre('save', function (next) {
  this.name = DOMPurify.sanitize(this.name);
  this.feedback = DOMPurify.sanitize(this.feedback);
  this.email = DOMPurify.sanitize(this.email);
  next();
});
frontend/src/components/ui/FeedbackForm.jsx (2)

24-57: Good improvements, but consider further refinements.

The handleSubmit function has been significantly improved:

  • Async/await is used correctly with proper error handling.
  • Loading state is managed appropriately.
  • Error handling and user feedback have been enhanced.

However, consider the following refinements:

  1. Move the fetch logic to a separate function for better separation of concerns.
  2. Use a more specific error message for network errors.
  3. Consider using a custom hook for form submission to make the component more readable.

Here's a suggested refactor:

const submitFeedback = async (feedbackData) => {
  const response = await fetch(`${API_URL}/feedback/create`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(feedbackData),
  });
  if (!response.ok) {
    const data = await response.json();
    throw new Error(data.message || "Failed to submit feedback");
  }
  return response.json();
};

const handleSubmit = async (e) => {
  e.preventDefault();
  setIsLoading(true);
  setError(null);
  try {
    await submitFeedback({ name, email, feedback });
    setSubmitted(true);
    // Reset form fields...
  } catch (error) {
    setError(error.message || "An unexpected error occurred");
    console.error("Feedback submission failed:", error);
  } finally {
    setIsLoading(false);
  }
};

Line range hint 1-171: Great improvements overall, consider final optimizations

The FeedbackForm component has been significantly enhanced:

  • Error handling and user feedback have been improved.
  • Loading state is now managed properly.
  • API integration uses environment variables correctly.
  • The UI now provides clear feedback during form submission.

Consider these final optimizations:

  1. Implement form validation before submission to improve user experience.
  2. Consider using a custom hook for form state management to reduce component complexity.
  3. Add aria-labels to form inputs for better accessibility.

Overall, excellent work on improving this component!

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ed67389 and b42bd8d.

📒 Files selected for processing (5)
  • backend/config/api.info.js (1 hunks)
  • backend/controller/feedback.controller.js (1 hunks)
  • backend/models/feedback.model.js (1 hunks)
  • backend/routes/feedbackRouter.js (1 hunks)
  • frontend/src/components/ui/FeedbackForm.jsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • backend/config/api.info.js
  • backend/controller/feedback.controller.js
  • backend/routes/feedbackRouter.js
🔇 Additional comments (7)
backend/models/feedback.model.js (2)

1-37: Excellent implementation of the feedback schema!

The schema structure is well-defined and includes all necessary fields with appropriate validations:

  • Name and feedback fields have length constraints.
  • Email field includes format validation using regex.
  • Timestamp tracking is implemented using both a createdAt field and the timestamps option.

This implementation aligns perfectly with the PR objectives and follows Mongoose best practices.


59-63: Model creation and export look good!

The Feedback model is correctly created using the defined schema and exported properly. This approach allows for easy importing in other parts of the application and provides flexibility for future expansion.

frontend/src/components/ui/FeedbackForm.jsx (5)

16-16: LGTM: Environment variable for API endpoint implemented correctly.

The use of import.meta.env.VITE_BACKEND_URI with a fallback to a localhost URL is a good practice. This allows for easy configuration across different environments.


21-22: LGTM: Error and loading states added.

The addition of error and isLoading state variables improves the component's ability to handle errors and provide feedback to the user during form submission.


142-142: LGTM: Dynamic button text based on loading state.

The button text now changes to "Submitting..." when the form is being submitted, providing clear feedback to the user about the ongoing action.


155-163: LGTM: Error message display added with animation.

The addition of an animated error message display improves user feedback and maintains consistency with the success message styling. This enhancement significantly improves the user experience during error scenarios.


24-57: Verify removal of sensitive data logging

Please confirm that any console logging of sensitive user data (name, email, feedback) has been removed from the handleSubmit function. If such logging exists, please remove it to protect user privacy.

@samar12-rad
Copy link
Contributor Author

Added pre save hook with validator.js library.
image

@samar12-rad
Copy link
Contributor Author

One conflict remaining for which i have already raised #72 . @RamakrushnaBiswal
image

@RamakrushnaBiswal
Copy link
Owner

@samar12-rad LGTM 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request gssoc-ext gssoc-extd program hacktoberfest accepted hacktoberfest-accepted repo level3 for 45 points
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants