Skip to content

Commit

Permalink
Add ambulance APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
haseebzaki-07 committed Oct 17, 2024
1 parent a71cc44 commit 22b35ce
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 34 deletions.
71 changes: 71 additions & 0 deletions Backend/Controllers/ambulanceController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const Ambulance = require("../Models/Ambulance");
const User = require("../Models/User");


// Controller to get all ambulances
const getAllAmbulances = async (req, res) => {
try {
const ambulances = await Ambulance.find();
res.json(ambulances);
} catch (error) {
res.status(500).json({ error: 'Server error, unable to fetch ambulances' });
}
};

// Controller to book an ambulance by a user
const bookAmbulance = async (req, res) => {
const { userId, ambulanceId } = req.body;

try {
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}

const ambulance = await Ambulance.findById(ambulanceId);
if (!ambulance) {
return res.status(404).json({ error: 'Ambulance not found' });
}

if (!ambulance.availabilityStatus) {
return res.status(400).json({ error: 'Ambulance is already booked' });
}

ambulance.availabilityStatus = false;
ambulance.user = user._id;
await ambulance.save();

user.bookedAmbulances.push(ambulance._id);
await user.save();

res.json({ message: 'Ambulance booked successfully', ambulance });
} catch (error) {
res.status(500).json({ error: 'Server error, unable to book ambulance' });
}
};

// Controller to create a new ambulance
const createAmbulance = async (req, res) => {
const { numberPlate, driverName, location } = req.body;

try {
const newAmbulance = new Ambulance({
numberPlate,
driverName,
location,
availabilityStatus: true, // By default, new ambulances are available
});

await newAmbulance.save();

res.json({ message: 'Ambulance created successfully', ambulance: newAmbulance });
} catch (error) {
res.status(500).json({ error: 'Server error, unable to create ambulance' });
}
};

module.exports = {
getAllAmbulances,
bookAmbulance,
createAmbulance,
};
12 changes: 12 additions & 0 deletions Backend/Models/Ambulance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ambulanceSchema = new Schema({
numberPlate: { type: String, required: true, unique: true },
driverName: { type: String, required: true },
location: { type: String, required: true },
availabilityStatus: { type: Boolean, default: true }, // Indicates if the ambulance is available
user: { type: Schema.Types.ObjectId, ref: 'User', required: false } // Reference to the user who booked the ambulance
});

module.exports = mongoose.model('Ambulance', ambulanceSchema);
14 changes: 7 additions & 7 deletions Backend/Models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
id: {type: String, unique: true},
username: String,
email: String,
password: String
});

module.exports = mongoose.model('User', userSchema);
id: { type: String, unique: true },
username: String,
email: String,
password: String,
bookedAmbulances: [{ type: Schema.Types.ObjectId, ref: 'Ambulance' }] // Reference to ambulances booked by the user
});
module.exports = mongoose.models.User || mongoose.model('User', userSchema);
66 changes: 39 additions & 27 deletions Backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,21 @@ app.use(bodyParser.json());

// MongoDB config below (Uncomment this code when mongoDB is created)

// mongoose.connect('add the connection string', { useNewUrlParser: true, useUnifiedTopology: true })
// .then(() => console.log('MongoDB connected'))
// .catch(err => console.log(err));
mongoose
.connect(
"mongodb+srv://haseebzaki:[email protected]/ambulance",
{ useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));

// Models
const User = require("./Models/User");
const {
createAmbulance,
getAllAmbulances,
bookAmbulance,
} = require("./Controllers/AmbulanceController");

app.get("/", (req, res) => {
res.send("AmbuFlow Server");
Expand All @@ -30,67 +39,66 @@ app.get("/", (req, res) => {
app.post("/signup", async (req, res) => {
const { id, username, email, password } = req.body;

// Hash the password using bcrypt
const hashedPassword = await bcrypt.hash(password, 10);
try {
const hashedPassword = await bcrypt.hash(password, 10);

// Uncomment this block when MongoDB is set up
/*
const user = new User({ id, username, email, password: hashedPassword });
const user = new User({ id, username, email, password: hashedPassword });

try {
await user.save();
res.status(201).send('User created successfully');
await user.save();

res.status(201).json({
message: "User created successfully",
user: {
id: user.id,
username: user.username,
email: user.email,
},
});
} catch (err) {
res.status(500).send('Error creating user: ' + err.message);
res.status(500).json({ error: "Error creating user: " + err.message });
}
*/

// Remove the below line when MongoDB is ready (for testing)
res.send("Signup route working");
});

// Login Route
app.post("/login", async (req, res) => {
const { username, password } = req.body;

// Uncomment the lines when MongoDB is created
/*

try {
const user = await User.findOne({ username });

if (!user) {
return res.status(401).send('User not found');
return res.status(401).send("User not found");
}

const isPasswordValid = await bcrypt.compare(password, user.password);

if (!isPasswordValid) {
return res.status(401).send('Invalid credentials');
return res.status(401).send("Invalid credentials");
}

const token = jwt.sign(
{ id: user.id, username: user.username },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
{ expiresIn: "1h" }
);

res.json({success: true, JWT_token: token , id: user.id});
res.json({ success: true, JWT_token: token, id: user.id });
} catch (err) {
res.status(500).send('Internal Server Error: ' + err.message);
res.status(500).send("Internal Server Error: " + err.message);
}
*/

// Hardcoded for testing purposes
const token = jwt.sign(
{ id: 1, username: "username" },
process.env.JWT_SECRET,
{ id: 1, username: "username" },
process.env.JWT_SECRET,
{ expiresIn: "1h" }
);

res.json({success: true, JWT_token: token , id: "testID893973983"});
res.json({ success: true, JWT_token: token, id: "testID893973983" });
});


// Middleware to protect routes
const authenticateToken = (req, res, next) => {
const token = req.headers["authorization"]?.split(" ")[1]; // Bearer token
Expand All @@ -113,6 +121,10 @@ app.get("/protected", authenticateToken, (req, res) => {
res.send("This is a protected route");
});

app.post("/ambulances/create", createAmbulance);
app.get("/ambulances", getAllAmbulances);
app.post("/ambulances/book", bookAmbulance);

app.listen(port, () => {
console.log(`Example app listening on http://localhost:${port}`);
});

0 comments on commit 22b35ce

Please sign in to comment.