Skip to content

Commit

Permalink
Hospital model and routes implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
abhudaym committed Feb 27, 2021
1 parent 2a3bd5b commit afde1ea
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 90 deletions.
44 changes: 27 additions & 17 deletions controllers/hospitalController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import asyncHandler from "express-async-handler";
import generateToken from "../utils/generateToken.js";
import Hospital from "../models/hospitalModel.js";
import axios from "axios";
import User from "../models/userModel.js";

const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
Expand All @@ -27,37 +28,28 @@ const registerHospital = asyncHandler(async (req, res) => {
const data = await axios.get(`http://ip-api.com/json`);
const lat = data.data.lat;
const lon = data.data.lon;
const { name, email, password, contactNo, address, availability } = req.body;

const { name, email, address, contactno, availability, password } = req.body;
const userExist = await Hospital.findOne({ email });

const user = await Hospital.create({
const hospital = await Hospital.create({
name,
email,
password,
contactNo,
address,
contactno,
ambulance: {
availability,
location: {
lat,
lon,
},
location: { lat, lon },
},
});
if (userExist) {
res.status(400);
throw new Error("User Already exists!");
} else {
res.json({
id: user._id,
name: user.name,
email: user.email,
contactNo: user.contactNo,
address: user.address,
ambulance: user.ambulance,
availability: user.availability,
token: generateToken(user._id),
id: hospital._id,
name: hospital.name,
token: generateToken(hospital._id),
});
}
});
Expand All @@ -67,4 +59,22 @@ const getHospitals = asyncHandler(async (req, res) => {
res.json(user);
});

export { registerHospital, getHospitals };
const addAmbulance = asyncHandler(async (req, res) => {
const hospital = await Hospital.findById(req.hospital._id);
const availability = req.body.availability;

const data = await axios.get(`http://ip-api.com/json`);
const lat = data.data.lat;
const lon = data.data.lon;
const location = {
lat,
lon,
};

hospital.ambulance.push({ availability, location });
hospital.save();

res.json(hospital);
});

export { registerHospital, getHospitals, addAmbulance };
8 changes: 0 additions & 8 deletions controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,16 +98,8 @@ const registerUser = asyncHandler(async (req, res) => {
});

const updateCircle = asyncHandler(async (req, res) => {
// to update circle, we need to find the user whose circle
// needs to be updated and then use spread operator to
// populate the existing array and add the new user.
const user2 = await User.findOne({ email: req.body.email });

// await User.findOneAndUpdate({
// _id: req.user._id,
// {$push: {circle: objCircle}}
// });

const user = await User.findById(req.user._id);
user.circle.push(user2);
user.save();
Expand Down
29 changes: 27 additions & 2 deletions middleware/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import jwt from "jsonwebtoken";
import User from "../models/userModel.js";
import asyncHandler from "express-async-handler";
import Hospital from "../models/hospitalModel.js";

const protect = asyncHandler(async (req, res, next) => {
const protectUser = asyncHandler(async (req, res, next) => {
let token;

if (
Expand All @@ -26,4 +27,28 @@ const protect = asyncHandler(async (req, res, next) => {
next();
});

export { protect };
const protectHospital = asyncHandler(async (req, res, next) => {
let token;

if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);

req.hospital = await Hospital.findById(decoded.id).select("-password");
} catch (error) {
res.status(401);
throw new Error("Not authorized, no token");
}
}
if (!token) {
res.status(401);
throw new Error("Not authorized, no token");
}
next();
});

export { protectUser, protectHospital };
8 changes: 3 additions & 5 deletions models/hospitalModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const hospitalSchema = mongoose.Schema(
type: String,
required: true,
},
contactNo: {
contactno: {
type: Number,
required: true,
},
Expand All @@ -25,18 +25,16 @@ const hospitalSchema = mongoose.Schema(
},
ambulance: [
{
availabilty: {
type: Boolean,
availability: {
type: mongoose.Schema.Types.String,
required: false,
},
location: {
lat: {
type: String,
required: false,
},
lon: {
type: String,
required: false,
},
},
},
Expand Down
4 changes: 3 additions & 1 deletion routes/hospitalRoutes.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import express from "express";
import {
addAmbulance,
getHospitals,
registerHospital,
} from "../controllers/hospitalController.js";
import { protect } from "../middleware/authMiddleware.js";
import { protectHospital } from "../middleware/authMiddleware.js";

const router = express.Router();
router.route("/").post(registerHospital).get(getHospitals);
router.route("/ambulance").put(protectHospital, addAmbulance);
// router.post("/login", authUser);

export default router;
4 changes: 2 additions & 2 deletions routes/userRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import {
updateCircle,
authUser,
} from "../controllers/userController.js";
import { protect } from "../middleware/authMiddleware.js";
import { protectUser } from "../middleware/authMiddleware.js";

const router = express.Router();
router.route("/").get(getUsers).post(registerUser);
router.route("/circle").post(protect, updateCircle);
router.route("/circle").post(protectUser, updateCircle);
router.post("/login", authUser);

export default router;
55 changes: 0 additions & 55 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import express from "express";
import dotenv from "dotenv";
import connectDB from "./config/db.js";
import User from "./models/userModel.js";
import userRoutes from "./routes/userRoutes.js";
import hospitalRoutes from "./routes/hospitalRoutes.js";

Expand All @@ -22,62 +21,8 @@ app.get("/", (req, res) => {
res.send("API is running!");
});

// app.use("/api/user", userRoutes);

// app.get(
// "/api/user",
// asyncHandler(async (req, res) => {
// const user = await User.find({});
// res.json(user);
// })
// );

// app.post(
// "/api/user",
// asyncHandler(async (req, res) => {
// const { name, email, password, email2 } = req.body;

// const user2 = await User.findOne({ email: email2 });

// const user = await User.create({
// name,
// email,
// password,
// circle: [
// {
// _id: user2._id,
// name: user2.name,
// email: user2.email,
// },
// ],
// });

// res.json({
// _id: user._id,
// name: user.name,
// email: user.email,
// circle: user.circle,
// });
// })
// );

// app.post(
// "/api/circle",
// asyncHandler(async (req, res) => {
// const { email } = req.body;

// const user = await User.findOne({ email })
// .populate("circles")
// .exec((err, circles) => {
// console.log("Populated User" + circles);
// });
// })
// );

const PORT = process.env.PORT || 5000;
app.listen(
PORT,
console.log(`Server running on ${PORT} in ${process.env.NODE_ENV}`)
);

// Build a route for adding people in a circle

0 comments on commit afde1ea

Please sign in to comment.