Skip to content

added an image upload route and modify the user model to be role specific #4

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1,984 changes: 1,963 additions & 21 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/jsonwebtoken": "^9.0.6",
"@types/multer": "^1.4.11",
"@types/node": "^20.14.9",
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^7.14.1",
Expand All @@ -49,8 +50,11 @@
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-validator": "^7.1.0",
"firebase": "^10.12.4",
"jsonwebtoken": "^9.0.2",
"mongodb": "^6.8.0",
"multer": "^1.4.5-lts.1",
"uuid": "^10.0.0",
"winston": "^3.13.0"
}
}
2 changes: 2 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import express from "express";
import userRoutes from "./routes/userRoutes";
import uploadRoutes from "./routes/uploadRoutes";
import cors from "cors";

const app = express();
Expand All @@ -16,5 +17,6 @@ app.get("/", (_req, res) => {
});

app.use("/user", userRoutes);
app.use("/file", uploadRoutes);

export default app;
19 changes: 19 additions & 0 deletions src/config/firebaseConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
apiKey: "AIzaSyAS1UZe5nxEfSVLQwDADOJbqyW7QjJcpu8",
authDomain: "medilog-ec19b.firebaseapp.com",
projectId: "medilog-ec19b",
storageBucket: "medilog-ec19b.appspot.com",
messagingSenderId: "1073972182214",
appId: "1:1073972182214:web:e91e9059604506d1e92bc7",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);

export const auth = getAuth(app);
export const db = getFirestore(app);
export const storage = getStorage(app);
29 changes: 29 additions & 0 deletions src/controllers/uploadContoller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Request, Response } from "express";
import { storage } from "../config/firebaseConfig";
import { ref, uploadBytes } from "firebase/storage";
import { v4 as uuidv4 } from "uuid";

export const uploadFile = async (
req: Request,
res: Response
): Promise<void> => {
const file = req.file;

if (!file) {
res.status(400).json({ message: "No file uploaded" });
return;
}

try {
const ext = file.originalname.split(".").slice(-1)[0];
const newFileName = `${uuidv4()}.${ext}`;

const storageRef = ref(storage, `uploads/${newFileName}`);
const metadata = await uploadBytes(storageRef, file.buffer);
const fileURL = `https://storage.googleapis.com/${storageRef.bucket}/${storageRef.fullPath}`;
res.json({ fileURL });
} catch (error) {
console.error("Error uploading file:", error);
res.status(500).json({ message: "Internal server error" });
}
};
105 changes: 80 additions & 25 deletions src/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,17 @@ const signUp = async (req: Request, res: Response): Promise<void> => {
email,
password,
dateOfBirth,
gender,
phoneNumber,
photo,
profileDescription,
role,
// Role-specific fields
pastHealthChallenge,
allergies,
currentMedication,
surgicalHistory,
extraDetails,
facility,
cadre,
firstTimeConsultationFee,
Expand All @@ -32,7 +40,9 @@ const signUp = async (req: Request, res: Response): Promise<void> => {
nationalIdentification,
medicalIndustryInsurance,
lAndA,
role,
BscRNCertificate,
nursingCouncilCertificate,
nurseLicense,
} = req.body;

try {
Expand All @@ -47,33 +57,78 @@ const signUp = async (req: Request, res: Response): Promise<void> => {
}

const hashedPassword = await hashPassword(password);
const newUser: User = {
id: uuidv4(),
fullName,
email,
password: hashedPassword,
dateOfBirth,
phoneNumber,
photo,
profileDescription,
facility,
cadre,
firstTimeConsultationFee,
followUpConsultationFee,
availableTime,
annualLicense,
fullLicense,
nationalIdentification,
medicalIndustryInsurance,
lAndA,
role: role || "patient",
};

let newUser: User;

if (role === "patient") {
newUser = {
id: uuidv4(),
fullName,
email,
password: hashedPassword,
dateOfBirth,
gender,
phoneNumber,
photo,
profileDescription,
role,
pastHealthChallenge,
allergies,
currentMedication,
surgicalHistory,
extraDetails,
};
} else if (role === "doctor") {
newUser = {
id: uuidv4(),
fullName,
email,
password: hashedPassword,
dateOfBirth,
gender,
phoneNumber,
photo,
profileDescription,
role,
facility,
cadre,
firstTimeConsultationFee,
followUpConsultationFee,
availableTime,
annualLicense,
fullLicense,
nationalIdentification,
medicalIndustryInsurance,
lAndA,
};
} else if (role === "nurse") {
newUser = {
id: uuidv4(),
fullName,
email,
password: hashedPassword,
dateOfBirth,
gender,
phoneNumber,
photo,
profileDescription,
role,
facility,
BscRNCertificate,
nursingCouncilCertificate,
nurseLicense,
extraDetails,
};
} else {
res.status(400).json({ message: "Invalid role specified" });
return;
}

await usersCollection.insertOne(newUser);

const token = jwt.sign({ id: newUser.id }, secretKey, { expiresIn: "1h" });

res.status(201).json({ token });
res.status(201).json({ userId: newUser.id, token });
} catch (err) {
res.status(500).json({ message: "Internal server error" });
}
Expand Down Expand Up @@ -142,7 +197,7 @@ const createUser = async (req: Request, res: Response): Promise<void> => {

const updateUserProfile = async (
req: Request,
res: Response,
res: Response
): Promise<void> => {
const { id } = req.params;
const updatedUser: User = req.body;
Expand All @@ -152,7 +207,7 @@ const updateUserProfile = async (
const usersCollection = getUsersCollection(db);
const result = await usersCollection.updateOne(
{ id },
{ $set: updatedUser },
{ $set: updatedUser }
);

if (result.modifiedCount > 0) {
Expand Down
29 changes: 26 additions & 3 deletions src/models/userModel.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
import bcrypt from "bcryptjs";
import { Db, Collection } from "mongodb";

export interface User {
export interface UserBase {
id: string;
fullName: string;
email: string;
password: string;
dateOfBirth: Date;
gender: string;
phoneNumber: string;
photo: string;
profileDescription: string;
role: "doctor" | "nurse" | "patient";
}
export interface PatientDetails {
pastHealthChallenge: string;
allergies: string;
currentMedication: string;
surgicalHistory: string;
extraDetails: string;
}
export interface DoctorDetails {
facility: string;
cadre: string;
firstTimeConsultationFee: number;
Expand All @@ -20,9 +31,21 @@ export interface User {
nationalIdentification: string;
medicalIndustryInsurance: string;
lAndA: string;
role: "doctor" | "nurse" | "patient";
}
export interface NurseDetails {
facility: string;
BscRNCertificate: string;
nursingCouncilCertificate: string;
nurseLicense: string;
extraDetails: string;
}

export type User = UserBase &
(
| ({ role: "doctor" } & DoctorDetails)
| ({ role: "nurse" } & NurseDetails)
| ({ role: "patient" } & PatientDetails)
);
let usersCollection: Collection<User>;

const getUsersCollection = (db: Db): Collection<User> => {
Expand All @@ -41,7 +64,7 @@ const hashPassword = async (password: string): Promise<string> => {

const comparePassword = async (
enteredPassword: string,
storedPassword: string,
storedPassword: string
): Promise<boolean> => {
return bcrypt.compare(enteredPassword, storedPassword);
};
Expand Down
10 changes: 10 additions & 0 deletions src/routes/uploadRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import express from "express";
import multer from "multer";
import { uploadFile } from "../controllers/uploadContoller";

const router = express.Router();
const upload = multer();

router.post("/upload", upload.single("file"), uploadFile);

export default router;
2 changes: 1 addition & 1 deletion src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ router.get("/", authenticateJWT, getUsers);
// router.post('/', authenticateJWT, createUser);
router.get("/me", authenticateJWT, getUserById);
router.delete("/:id", authenticateJWT, deleteUser);
router.get("/:id", authenticateJWT, updateUserProfile);
router.put("/:id", authenticateJWT, updateUserProfile);

export default router;