Skip to content

Commit c64382e

Browse files
committed
refactor: pharmacy service add
1 parent ea594d2 commit c64382e

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

src/services/pharmacy.service.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { useImperativeHandle } from 'react';
2+
import User from '../models/User.js';
3+
import bcrypt from 'bcrypt';
4+
5+
const createPharmacist = async (data) => {
6+
const password = data.password || 'pharmacist@123';
7+
const hashedPassword = await bcrypt.hash(password, 10);
8+
9+
const pharmacist = new User ({
10+
...data,
11+
password: hashedPassword,
12+
role: 'pharmacist',
13+
});
14+
15+
return await pharmacist.save();
16+
};
17+
18+
const changePassword = async (userId, oldPassword, newPassword) => {
19+
const pharmacist = await User.findById(userId);
20+
if(!pharmacist) throw new Error('Pharmacist not found');
21+
22+
const isMatch = await bcrypt.compare(oldPassword, pharmacist.password);
23+
if(!isMatch) throw new Error('Old password is incorrect');
24+
25+
pharmacist.password = await bcrypt.hash(newPassword, 10);
26+
await pharmacist.save();
27+
28+
return { message: 'Password changed successfully' };
29+
};
30+
31+
const getPharmacists = async () => {
32+
return await User.find({ role: 'pharmacist' });
33+
};
34+
35+
const updatePharmacist = async (id, data) => {
36+
if(data.password) {
37+
data.password = await bcrypt.hash(data.password, 10);
38+
}
39+
40+
const pharmacist = await User.findOneAndUpdate(
41+
{ _id: id, role: 'pharmacist' },
42+
data,
43+
{ new: true, runValidators: true }
44+
);
45+
46+
if(!pharmacist) throw new Error('Pharmacist not found');
47+
48+
return pharmacist;
49+
};
50+
51+
const deletePharmacist = async (id) => {
52+
const pharmacist = await User.findOneAndDelete({ _id: id, role: 'pharmacist' });
53+
if(!pharmacist) throw new Error('Pharmacist not found');
54+
55+
return { message: 'Pharmacist deleted successfully'};
56+
};
57+
58+
export default {
59+
createPharmacist,
60+
changePassword,
61+
getPharmacists,
62+
updatePharmacist,
63+
deletePharmacist
64+
};

0 commit comments

Comments
 (0)