-
-
Notifications
You must be signed in to change notification settings - Fork 101
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
Created Feedback Submission System #65
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
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 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. WalkthroughThe changes in this pull request involve updates to the feedback functionality within the application. Key modifications include the removal of the Changes
Possibly related PRs
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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! 😊 |
|
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
- Understand the implications of revoking this secret by investigating where it is used in your code.
- Replace and store your secrets safely. Learn here the best practices.
- Revoke and rotate these secrets.
- 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
- following these best practices for managing and storing secrets including API keys and other credentials
- install secret detection on pre-commit to catch secret before it leaves your machine and ease remediation.
🦉 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.
There was a problem hiding this 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 importThe
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.
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);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 thecreateFeedback
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:
- Enhance the feedback schema with more specific validation rules.
- Add input sanitization to prevent XSS attacks.
- Implement more granular error handling, especially for database operations.
- Improve error logging by including stack traces.
- 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
📒 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 setupThe Express router is correctly initialized, and the POST route for creating feedback is properly defined using the imported createFeedback controller.
20-20
: LGTM: Router exportThe 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 improvementThe 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:
- Using async/await for handling the asynchronous fetch call.
- Properly stringifying the body of the request.
- Checking the response status before proceeding.
- Maintaining the existing success handling logic.
backend/routes/index.js
Outdated
@@ -3,6 +3,7 @@ const Reservation = require("../models/reservation.model"); | |||
|
|||
const router = express.Router(); | |||
|
|||
router.use("/feedback", require("./feedbackRouter")); |
There was a problem hiding this comment.
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);
e.preventDefault(); | ||
console.log(`Name: ${name}, Email: ${email}, Feedback: ${feedback}`); | ||
const response = await fetch("http://localhost:3000/api/feedback/create", { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
resolve @coderabit suggestions |
@GitGuardian scan |
@RamakrushnaBiswal , performed code rabbit changes, removed risks created by git guardian |
There was a problem hiding this 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:
- Add descriptions for each endpoint to explain their purpose.
- Include information about expected response formats and status codes.
- Define possible error responses and their meanings.
- As the API grows, add new endpoints to this configuration file.
- Consider adding rate limiting information if applicable.
- 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:
- Remove the commented-out example entirely if it's no longer needed.
- Move this example to a separate documentation file or README.
- 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
📒 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
, andtimestamps
enhances data integrity and provides useful metadata.To fully complete the implementation:
- Consider adding input sanitization as suggested earlier.
- Ensure that this model is properly integrated with the backend routes, especially the POST route at /submit-feedback mentioned in the PR objectives.
- 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:
- The
name
field has appropriate length constraints (2-100 characters).- The
- 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.
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? |
ok then @samar12-rad go for it |
@RamakrushnaBiswal . i create the issue. Also, is this PR completed? |
resolve the conflicts please @samar12-rad |
@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. |
There was a problem hiding this 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
andfeedback
fields to prevent XSS attacks. This addresses the previous suggestion for input sanitization.Consider the following minor improvements:
- As mentioned in the comment, replace this basic sanitization with a robust library like DOMPurify for production use.
- 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:
- Move the fetch logic to a separate function for better separation of concerns.
- Use a more specific error message for network errors.
- 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 optimizationsThe 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:
- Implement form validation before submission to improve user experience.
- Consider using a custom hook for form state management to reduce component complexity.
- 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
📒 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 thetimestamps
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
andisLoading
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 loggingPlease 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.
One conflict remaining for which i have already raised #72 . @RamakrushnaBiswal |
@samar12-rad LGTM 🚀 |
e5492ae
into
RamakrushnaBiswal:main
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
Improvements
Bug Fixes