Skip to content

Commit 8c19291

Browse files
committed
feat: add pharmacist CRUD functionality; routing pending
1 parent eb1b177 commit 8c19291

1 file changed

Lines changed: 95 additions & 0 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import User from '../models/User.js';
2+
import bcrypt from 'bcrypt';
3+
4+
const createPharmacist = async (req,res) => {
5+
try {
6+
const password = req.body.password || 'pharmacist@123';
7+
const hashedPassword = await bcrypt.hash(password, 10);
8+
9+
const pharmacist = new User({
10+
...req.body,
11+
password: hashedPassword,
12+
role: 'pharmacist'
13+
});
14+
15+
await pharmacist.save();
16+
res.status(201).json(pharmacist);
17+
} catch (err) {
18+
res.status(400).json({ message: err.message });
19+
}
20+
};
21+
22+
const changePassword = async (req,res) => {
23+
try {
24+
const pharmacist = await User.findById(req.user.id);
25+
const { oldPassword, newPassword } = req.body;
26+
27+
const isMatch = await bcrypt.compare(oldPassword, pharmacist.password);
28+
if (!isMatch) return res.status(400).json({ message: 'Old password is incorrect' });
29+
30+
pharmacist.password = await bcrypt.hash(newPassword, 10);
31+
await pharmacist.save();
32+
33+
res.status(200).json({ message: 'Password updated successfully' });
34+
} catch (err) {
35+
res.status(500).json({ message: err.message });
36+
}
37+
};
38+
39+
const getPharmacists = async (req,res) => {
40+
try {
41+
const pharmacist = await User.find({ role: 'pharmacist' });
42+
res.json(pharmacist);
43+
} catch (err) {
44+
res.status(500).json({ message: err.message });
45+
}
46+
};
47+
48+
const updatePharmacist = async (req,res) => {
49+
try {
50+
const { id } = req.params;
51+
52+
if (req.body.password) {
53+
req.body.password = await bcrypt.hash(req.body.password, 10);
54+
55+
}
56+
57+
const pharmacist = await User.findOneAndUpdate(
58+
{ _id: id, role: 'pharmacist' },
59+
req.body,
60+
{ new: true, runValidators: true }
61+
);
62+
63+
if (!pharmacist) {
64+
return res.status(404).json({ message: 'Pharmacist not found' });
65+
}
66+
67+
res.json(pharmacist);
68+
} catch (err) {
69+
res.status(400).json({ message: err.message });
70+
}
71+
};
72+
73+
const deletePharmacist = async (req,res) => {
74+
try {
75+
const { id } = req.params;
76+
77+
const pharmacist = await User.findOneAndDelete({ _id: id, role: 'pharmacist' });
78+
79+
if (!pharmacist) {
80+
return res.status(400).json({ message: 'Pharmacist not found' });
81+
}
82+
83+
res.json({ message: 'Pharmacist deleted successfully' });
84+
} catch (err) {
85+
res.status(500).json({ message: err.message });
86+
}
87+
};
88+
89+
export {
90+
createPharmacist,
91+
changePassword,
92+
getPharmacists,
93+
updatePharmacist,
94+
deletePharmacist
95+
};

0 commit comments

Comments
 (0)