Skip to content
Snippets Groups Projects
Commit 503d719e authored by Tonge, Marcus A (UG - Comp Sci & Elec Eng)'s avatar Tonge, Marcus A (UG - Comp Sci & Elec Eng)
Browse files

Booking service finished

parent cf7f482f
No related branches found
No related tags found
No related merge requests found
.env 0 → 100644
APP_NOTIFICATION_SERVICE_ENDPOINT = ''
JWT_SECRET = ''
\ No newline at end of file
const express = require("express"); const express = require("express");
const bodyParser = require("body-parser"); const router = express.Router();
const mongoose = require("mongoose"); const Booking = require("../schema/schema");
const jwt = require("jsonwebtoken");
const axios = require("axios"); const axios = require("axios");
const jwt = require("jwt-simple");
const app = express(); const jwtAlgorithm = "HS512";
const port = process.env.PORT || 3000; const notificationURL = process.env.APP_NOTIFICATION_SERVICE_ENDPOINT;
// MongoDB Connection
mongoose.connect("mongodb://localhost/booking-service", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
console.log("Connected to MongoDB!");
});
// Booking Schema
const bookingSchema = new mongoose.Schema({
user_id: { type: String, required: true },
location_id: { type: String, required: true },
title: { type: String, required: true },
street_address: { type: String, required: true },
start_time: { type: Date, required: true },
end_time: { type: Date, required: true },
});
const Booking = mongoose.model("Booking", bookingSchema);
// Middleware // Middleware
app.use(bodyParser.urlencoded({ extended: false })); // app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // app.use(bodyParser.json());
// Routes // Routes
app.post("/bookings/create", async (req, res) => { router.post("/bookings/create", async (req, res) => {
try { try {
const { const {
user_id, user_id,
...@@ -46,13 +23,30 @@ app.post("/bookings/create", async (req, res) => { ...@@ -46,13 +23,30 @@ app.post("/bookings/create", async (req, res) => {
end_time, end_time,
} = req.body; } = req.body;
// Check if there is enough free space in the location // Get the JWT secret from the environment variables
const locationResponse = await axios.get( const secretKey = process.env.JWT_SECRET;
`http://location-service/check/${location_id}` // If this is not set we want to throw an error as this is required to retrieve the user
); // id from the provided token.
if (!locationResponse.data.success) { if (secretKey == null) {
return res.status(400).json({ message: locationResponse.data.message }); console.error("JWT_SECRET is not set in the environment variables");
return res
.status(500)
.send("JWT_SECRET is not set in the environment variables");
} }
// Get the token from the request headers
const token = req.headers.authorization.split(" ")[1];
// Decode this token with the secret key
const payload = jwt.decode(token, secretKey, false, jwtAlgorithm);
// Get the user id from the decoded token payload.
const userId = payload.id;
// // Check if there is enough free space in the location
// const locationResponse = await axios.get(
// `http://location-service/check/${location_id}`
// );
// if (!locationResponse.data.success) {
// return res.status(400).json({ message: locationResponse.data.message });
// }
// Create new booking // Create new booking
const booking = new Booking({ const booking = new Booking({
...@@ -65,33 +59,63 @@ app.post("/bookings/create", async (req, res) => { ...@@ -65,33 +59,63 @@ app.post("/bookings/create", async (req, res) => {
}); });
const savedBooking = await booking.save(); const savedBooking = await booking.save();
const date = end_time;
const options = {
hour: "numeric",
minute: "numeric",
second: "numeric",
year: "numeric",
month: "long",
day: "numeric",
};
const formattedDate = date.toLocaleDateString("en-US", options);
// Send notification to notifications service // Send notification to notifications service
await axios.post("http://notifications-service/create", { await axios.post(`${notificationURL}/create`, {
message: "New booking created", method: "DELETE",
booking_id: savedBooking._id, headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: {
user_id: userId,
title: `Booking Created at ${title}`,
description: `You made a booking at ${street_address}. It expires at ${formattedDate}.`,
},
}); });
// Decrement free space in location // // Decrement free space in location
await axios.put(`http://location-service/update/${location_id}`, { // await axios.put(`http://location-service/update/${location_id}`, {
action: "decrement", // action: "decrement",
}); // });
res.json({ success: true, booking: savedBooking }); res.status(200).send(savedBooking);
} catch (error) { } catch (error) {
console.log(error); console.log(error);
res.status(500).json({ message: "Internal server error" }); res.status(500).json({ message: "Internal server error" });
} }
}); });
app.put("/bookings/extend/:id", async (req, res) => { router.put("/bookings/extend/:id", async (req, res) => {
try { try {
const { id } = req.params; const { id } = req.params;
const { extension_time } = req.body; const { extension_time } = req.body;
// Get user_id from token // Get the JWT secret from the environment variables
const secretKey = process.env.JWT_SECRET;
// If this is not set we want to throw an error as this is required to retrieve the user
// id from the provided token.
if (secretKey == null) {
console.error("JWT_SECRET is not set in the environment variables");
return res
.status(500)
.send("JWT_SECRET is not set in the environment variables");
}
// Get the token from the request headers
const token = req.headers.authorization.split(" ")[1]; const token = req.headers.authorization.split(" ")[1];
const decodedToken = jwt.verify(token, "secret_key"); // Decode this token with the secret key
const user_id = decodedToken.user_id; const payload = jwt.decode(token, secretKey, false, jwtAlgorithm);
// Get the user id from the decoded token payload.
const user_id = payload.id;
// Find booking with correct id and user_id // Find booking with correct id and user_id
const booking = await Booking.findOne({ _id: id, user_id }); const booking = await Booking.findOne({ _id: id, user_id });
...@@ -100,11 +124,35 @@ app.put("/bookings/extend/:id", async (req, res) => { ...@@ -100,11 +124,35 @@ app.put("/bookings/extend/:id", async (req, res) => {
} }
// Increment end_time by extension_time // Increment end_time by extension_time
booking.end_time = new Date( // booking.end_time = new Date(
booking.end_time.getTime() + extension_time * 60 * 1000 // booking.end_time.getTime() + extension_time * 60 * 1000
); // );
booking.end_time = extension_time;
const savedBooking = await booking.save(); const savedBooking = await booking.save();
// Booking extended notification
const date = booking.end_time;
const options = {
hour: "numeric",
minute: "numeric",
second: "numeric",
year: "numeric",
month: "long",
day: "numeric",
};
const formattedDate = date.toLocaleDateString("en-US", options);
await axios.post(`${notificationURL}/create`, {
method: 'POST',
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: {
user_id: userId,
title: `Booking Extended`,
description: `Your booking at ${booking.street_address} has been extended to ${formattedDate}.`,
},
});
res.json({ success: true, booking: savedBooking }); res.json({ success: true, booking: savedBooking });
} catch (error) { } catch (error) {
console.log(error); console.log(error);
...@@ -112,12 +160,24 @@ app.put("/bookings/extend/:id", async (req, res) => { ...@@ -112,12 +160,24 @@ app.put("/bookings/extend/:id", async (req, res) => {
} }
}); });
app.get("/bookings/getAllBookings", async (req, res) => { router.get("/bookings/getAllBookings", async (req, res) => {
try { try {
// Get user_id from token // Get the JWT secret from the environment variables
const secretKey = process.env.JWT_SECRET;
// If this is not set we want to throw an error as this is required to retrieve the user
// id from the provided token.
if (secretKey == null) {
console.error("JWT_SECRET is not set in the environment variables");
return res
.status(500)
.send("JWT_SECRET is not set in the environment variables");
}
// Get the token from the request headers
const token = req.headers.authorization.split(" ")[1]; const token = req.headers.authorization.split(" ")[1];
const decodedToken = jwt.verify(token, "secret_key"); // Decode this token with the secret key
const user_id = decodedToken.user_id; const payload = jwt.decode(token, secretKey, false, jwtAlgorithm);
// Get the user id from the decoded token payload.
const user_id = payload.id;
// Find all bookings for user_id // Find all bookings for user_id
const bookings = await Booking.find({ user_id }); const bookings = await Booking.find({ user_id });
...@@ -142,25 +202,34 @@ setInterval(async () => { ...@@ -142,25 +202,34 @@ setInterval(async () => {
// Send notification to notifications service for each deleted booking // Send notification to notifications service for each deleted booking
for (let i = 0; i < expiredBookings.length; i++) { for (let i = 0; i < expiredBookings.length; i++) {
await axios.post("http://notifications-service/create", { await axios.post(`${notificationURL}/create`, {
message: "Booking expired", method: 'POST',
booking_id: expiredBookings[i]._id, headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: {
user_id: userId,
title: `Booking Expired`,
description: `Your booking at ${expiredBookings.street_address} has now expired.`,
},
}); });
// Increment free space in location // // Increment free space in location
await axios.put( // await axios.put(
`http://location-service/update/${expiredBookings[i].location_id}`, // `http://location-service/update/${expiredBookings[i].location_id}`,
{ // {
action: "increment", // action: "increment",
} // }
); // );
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} }
}, 60000); }, 60000);
// Start server // // Start server
app.listen(port, () => { // router.listen(port, () => {
console.log(`Booking service listening at http://localhost:${port}`); // console.log(`Booking service listening at http://localhost:${port}`);
}); // });
module.exports = router;
...@@ -10,4 +10,4 @@ const bookingSchema = new mongoose.Schema({ ...@@ -10,4 +10,4 @@ const bookingSchema = new mongoose.Schema({
}); });
const Booking = mongoose.model('Booking',bookingSchema); const Booking = mongoose.model('Booking',bookingSchema);
module.exports = Booking; module.exports = Booking;
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment