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

Added Backend Route for Café Reservation Form and .env Configuration #42

Merged
merged 19 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
db7237b
Added backend form submission for Reservation
samar12-rad Oct 2, 2024
8b7f3b4
Merge branch 'main' of https://github.com/samar12-rad/PlayCafe into r…
samar12-rad Oct 2, 2024
1834450
Tried to fix deployement issues
samar12-rad Oct 3, 2024
13ca5e7
Fixed package.json
samar12-rad Oct 3, 2024
9c4027e
Setup backend with mvc architechture added proper routing
samar12-rad Oct 3, 2024
1fd66bf
restructured
samar12-rad Oct 3, 2024
39dc5ab
Merge branch 'main' of samar12-rad/PlayCafe into Backend-Restructuring
samar12-rad Oct 3, 2024
4af9a60
Setup backend with mvc architechture added proper routing
samar12-rad Oct 3, 2024
5bf789d
Setup backend with mvc architechture added proper routing
samar12-rad Oct 3, 2024
269fcc0
Setup backend with mvc architechture added proper routing for future
samar12-rad Oct 3, 2024
51f78ac
Removed env mongo signature
samar12-rad Oct 3, 2024
367a8f4
resolved gitrrabit conflicts
samar12-rad Oct 3, 2024
ab8d55e
resolved gitrrabit in index.js
samar12-rad Oct 3, 2024
35d21d2
Merge branch 'main' of https://github.com/samar12-rad/PlayCafe into B…
samar12-rad Oct 3, 2024
4a71b38
added env.example
samar12-rad Oct 3, 2024
3a45128
Merge branch 'main' of https://github.com/samar12-rad/PlayCafe into r…
samar12-rad Oct 3, 2024
4d880aa
Merge branch 'Backend' of https://github.com/samar12-rad/PlayCafe int…
samar12-rad Oct 3, 2024
888aa5c
Made reservation portal which stores reservation data in backend
samar12-rad Oct 3, 2024
1271b72
removed .env, added .env.example
samar12-rad Oct 3, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
35 changes: 35 additions & 0 deletions backend/controller/reservation.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const { z } = require("zod");
const Reservation = require("../models/reservation.model");

// Define the Zod schema for reservation validation
const reservationSchema = z.object({
Guests: z.string(),
Date: z.string(),
Time: z.string(),
});
RamakrushnaBiswal marked this conversation as resolved.
Show resolved Hide resolved

async function createReservation(req, res) {
try {
// Validate the request body against the schema
const validationResult = reservationSchema.safeParse(req.body);

if (!validationResult.success) {
return res.status(400).json({ message: validationResult.error.errors });
}

// Create the reservation if validation passes
const reservation = await Reservation.create({
Guests: validationResult.data.Guests,
Date: validationResult.data.Date,
Time: validationResult.data.Time,
});

res.status(201).json(reservation);
} catch (error) {
res.status(400).json({ message: error.message });
}
}
RamakrushnaBiswal marked this conversation as resolved.
Show resolved Hide resolved

module.exports = {
createReservation,
};
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

.env file is missing from the project root.

The application is configured to use environment variables via the dotenv package, as evidenced by the usage of require("dotenv").config(); and process.env.MONGO_URI. However, the .env file is not present in the repository. To ensure proper configuration and functionality:

  1. Create a .env file in the project root.
  2. Define necessary environment variables (e.g., MONGO_URI) within the .env file.
  3. Add .env to .gitignore to prevent accidental commits of sensitive information.
🔗 Analysis chain

Verify .env file implementation and usage.

The PR objectives mention implementing a .env file for secure management of environment variables. However, this file doesn't directly use any environment variables. To ensure proper setup:

  1. Confirm that a .env file has been created in the project root.
  2. Verify that sensitive information (like database connection strings) is stored in the .env file.
  3. Ensure that the .env file is added to .gitignore to prevent accidental commits.

Run the following script to check for .env file and its usage:

If the .env file is not found or environment variables are not used, consider updating the PR description or implementing the .env configuration as described in the PR objectives.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for .env file and its usage
if [ -f .env ]; then
  echo ".env file exists"
  # Print the .env file structure without revealing values
  sed 's/=.*/=****/' .env
else
  echo ".env file not found"
fi

# Check for environment variable usage in the codebase
rg -i '(process\.env\.|dotenv)'

Length of output: 242

22 changes: 20 additions & 2 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
const express = require("express");
const cors = require("cors");
const app = express();
const port = 3000;
require("dotenv").config();
const mongoose = require("mongoose");
const { createReservation } = require("./controller/reservation.controller");
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

createReservation is not exported from ./controller/reservation.controller.js

The createReservation function is not exported in ./controller/reservation.controller.js. Please ensure that it is properly exported to make it available for the route handler.

  • File: ./backend/controller/reservation.controller.js
🔗 Analysis chain

Verify that createReservation is correctly exported from reservation.controller

To ensure that the createReservation function is properly exported and available for the route handler, please confirm that it is correctly exported in ./controller/reservation.controller.js.

Run the following script to verify the export:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if 'createReservation' is exported from 'reservation.controller.js'

# Test: Search for 'exports.createReservation' or 'module.exports' containing 'createReservation'

grep -E 'exports\.createReservation|module\.exports.*createReservation' ./controller/reservation.controller.js

# Also check for ES6 exports
grep -E 'export\s+(function|const|let|var)\s+createReservation' ./controller/reservation.controller.js

Length of output: 361


Script:

#!/bin/bash
# Description: Locate 'reservation.controller.js' within the codebase

fd 'reservation.controller.js' .

Length of output: 79


Script:

#!/bin/bash
# Description: Verify if 'createReservation' is exported from the correct 'reservation.controller.js' file

# Check for CommonJS exports
grep -E 'exports\.createReservation|module\.exports.*createReservation' ./backend/controller/reservation.controller.js

# Check for ES6 exports
grep -E 'export\s+(function|const|let|var)\s+createReservation' ./backend/controller/reservation.controller.js

Length of output: 233


app.get("/", (req, res) => res.send("Hello World!"));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
app.use(cors({}));

app.use(express.json());

mongoose
.connect(process.env.MONGO_URI)
.then(() => {
console.log("Connected to MongoDB");
})
.catch((error) => {
console.error("Database connection failed:", error);
});
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

Ensure MONGO_URI is defined before attempting to connect to MongoDB

If process.env.MONGO_URI is undefined, mongoose.connect may attempt to connect using an undefined URI, leading to connection errors that may be hard to debug. It's advisable to check that MONGO_URI is defined before attempting to connect and provide a meaningful error message if it's not.

Apply this diff to add a check:

+if (!process.env.MONGO_URI) {
+  console.error("Error: MONGO_URI is not defined in environment variables.");
+  process.exit(1);
+}
 mongoose
   .connect(process.env.MONGO_URI)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
mongoose
.connect(process.env.MONGO_URI)
.then(() => {
console.log("Connected to MongoDB");
})
.catch((error) => {
console.error("Database connection failed:", error);
});
if (!process.env.MONGO_URI) {
console.error("Error: MONGO_URI is not defined in environment variables.");
process.exit(1);
}
mongoose
.connect(process.env.MONGO_URI)
.then(() => {
console.log("Connected to MongoDB");
})
.catch((error) => {
console.error("Database connection failed:", error);
});


app.post("/create-reservation", createReservation);

app.listen(port, () => console.log(`Server is running on port ${port}!`));
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

Make the server port configurable via environment variables

Currently, the server port is hardcoded to 3000. To allow greater flexibility and ease of deployment across different environments, consider using an environment variable for the port number.

Apply this diff to make the port configurable:

-const port = 3000;
+const port = process.env.PORT || 3000;

 app.listen(port, () => console.log(`Server is running on port ${port}!`));

Committable suggestion was skipped due to low confidence.

21 changes: 21 additions & 0 deletions backend/models/reservation.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const reservationSchema = new Schema({
Guests: {
type: String,
required: true,
},
Date: {
type: String,
required: true,
},
Time: {
type: String,
required: true,
},
});
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

Enhance schema definition for better data integrity and consistency

While the basic structure is correct, consider the following improvements:

  1. Use lowercase for field names (e.g., guests, date, time) to follow JavaScript conventions.
  2. Change the Guests field to a Number type for easier querying and validation.
  3. Use the Date type for the Date field to leverage MongoDB's date operations.
  4. Add more specific validation to ensure data integrity.

Here's a suggested refactor:

const reservationSchema = new Schema({
  guests: {
    type: Number,
    required: true,
    min: [1, 'At least one guest is required'],
    max: [20, 'Maximum 20 guests allowed']
  },
  date: {
    type: Date,
    required: true,
    min: [new Date(), 'Date must be in the future']
  },
  time: {
    type: String,
    required: true,
    match: [/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/, 'Time must be in HH:MM format']
  }
});

This refactor improves type safety, adds validation, and follows naming conventions.


const Reservation = mongoose.model("Reservation", reservationSchema);

module.exports = Reservation;
10 changes: 9 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "nodemon index.js",
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 3, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding separate scripts for development and production

While using nodemon for auto-reloading during development is great, it's not typically used in production. Consider adding separate scripts for development and production:

 "scripts": {
-    "start": "nodemon index.js",
+    "start": "node index.js",
+    "dev": "nodemon index.js",
     "test": "echo \"Error: no test specified\" && exit 1"
 },

This way, npm start can be used for production, and npm run dev for development with auto-reloading.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"start": "nodemon index.js",
"start": "node index.js",
"dev": "nodemon index.js",

Copy link
Owner

Choose a reason for hiding this comment

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

@samar12-rad
add this
"start": "node index.js",
"dev": "nodemon index.js",

other wise give error while deploying

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"express": "^4.21.0"
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.0",
RamakrushnaBiswal marked this conversation as resolved.
Show resolved Hide resolved
"mongoose": "^8.7.0",
"zod": "^3.23.8"
},
"devDependencies": {
"nodemon": "^3.1.7"
RamakrushnaBiswal marked this conversation as resolved.
Show resolved Hide resolved
}
}
45 changes: 42 additions & 3 deletions frontend/src/components/Pages/Register.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,45 @@
import { useEffect, useState } from "react";
import pic from "../../assets/img/abt1.jpg";
import pic2 from "../../assets/img/abt1.png";
import pic3 from "../../assets/img/abt2.png";
import pic4 from "../../assets/img/abt3.png";
import pic5 from "../../assets/img/abt4.png";

export default function Register() {
const [Guests, setGuests] = useState();
const [Date, setDate] = useState("");
const [Time, setTime] = useState("");
RamakrushnaBiswal marked this conversation as resolved.
Show resolved Hide resolved

useEffect(() => {
console.log(Guests);
}, [Guests]);

useEffect(() => {
console.log(Date);
}, [Date]);

useEffect(() => {
console.log(Time);
}, [Time]);

const handleSubmit = (e) => {
e.preventDefault();
fetch("http://localhost:3000/create-reservation", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
Guests,
Date,
Time,
}),
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));
};
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 2, 2024

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 and provide user feedback

The API endpoint URL "http://localhost:3000/create-reservation" is hardcoded in the fetch call. To enhance flexibility and security, especially in different environments (development, staging, production), consider using environment variables to store the base URL of your API.

Also, currently, the response from the server is logged to the console, and there's no feedback to the user upon successful submission or error. Providing user feedback improves user experience.

Apply this diff to use an environment variable for the API endpoint:

-    fetch("http://localhost:3000/create-reservation", {
+    fetch(`${process.env.REACT_APP_API_BASE_URL}/create-reservation`, {

Ensure you have REACT_APP_API_BASE_URL defined in your .env file.

Additionally, handle user feedback by updating the UI based on the response:

-  .then((data) => console.log(data))
+  .then((data) => {
+    // Handle success (e.g., show a success message or redirect)
+    console.log("Reservation successful:", data);
+  })

And handle errors appropriately:

-  .catch((error) => console.log(error));
+  .catch((error) => {
+    // Handle error (e.g., show an error message to the user)
+    console.error("Reservation failed:", error);
+  });

Committable suggestion was skipped due to low confidence.

Copy link
Owner

Choose a reason for hiding this comment

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

@samar12-rad
add the URL in .env file

http://localhost:3000

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!


return (
<>
<div className="w-full mx-auto mt-10 lg:mt-0 md:mt-0">
Expand Down Expand Up @@ -46,6 +81,7 @@ export default function Register() {
</label>
<select
id="guests"
onChange={(e) => setGuests(e.target.value)}
RamakrushnaBiswal marked this conversation as resolved.
Show resolved Hide resolved
className="flex h-10 w-full items-center rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
>
<option value="">Select number of guests</option>
Expand All @@ -67,7 +103,8 @@ export default function Register() {
<input
type="date"
id="date"
className="flex h-10 w-full items-center rounded-md border border-input bg-white px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
onChange={(e) => setDate(e.target.value)}
className="flex h-10 w-full items-center rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
</div>
Expand All @@ -80,6 +117,7 @@ export default function Register() {
</label>
<select
id="time"
onChange={(e) => setTime(e.target.value)}
className="flex h-10 w-full items-center rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
>
<option value="">Select time</option>
Expand All @@ -93,6 +131,7 @@ export default function Register() {
<button
className="inline-flex items-center justify-center p-4 bg-[#D9D9D9] hover:bg-[#C9C9C9]"
type="submit"
onClick={handleSubmit}
>
Reserve Now
</button>
Expand All @@ -101,8 +140,8 @@ export default function Register() {
</div>
</section>
<h1 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-bold tracking-tighter text-amber-100 bg-green-900 p-5 text-center">
Popular Board Games
</h1>
Popular Board Games
</h1>
<div className="mt-8 w-full flex justify-center bg-white ">
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 mt-8 mb-10">
<div
Expand Down