Skip to content

Commit

Permalink
feat: add edit and delete admin endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
ditramadia committed Nov 16, 2023
1 parent 4c17071 commit 2545c10
Showing 1 changed file with 81 additions and 3 deletions.
84 changes: 81 additions & 3 deletions src/routes/admin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import express from 'express';
import bcrypt from 'bcrypt';
import accessValidation from '../middleware/accessValidation';
import { PrismaClient } from '@prisma/client';

Expand Down Expand Up @@ -42,20 +43,97 @@ router.get('/:id', accessValidation, async (req, res) => {
admin_id: true,
username: true,
email: true,
password: false,
},
});

res.json({
message: 'Admins retrieved successfully',
message: 'Admin retrieved successfully',
result,
});
} catch (error) {
console.error(error);
res.status(500).json({
message: 'An error occurred while retrieving the exercises',
message: 'An error occurred while retrieving the admin',
});
}
});

// Create admin
router.post('/create', accessValidation, async (req, res) => {
const {username, email, password} = req.body;

// Hash password
const hashedPassword = await bcrypt.hash(password, 10);

try {
await prisma.admin.create({
data: {
username,
email,
password: hashedPassword,
}
});

return res.status(200).json({
message: 'Admin successfully created'
});
} catch (error) {
return res.status(500).json({
message: 'An error occurred while creating admin'
});
}
});

// Update admin
router.put('/edit/:id', accessValidation, async (req, res) => {
const { id } = req.params;
const { username, email, password } = req.body;

// Hash password
const hashedPassword = await bcrypt.hash(password, 10);

try {
await prisma.admin.update({
where: {
admin_id: parseInt(id)
}, data: {
username,
email,
password: hashedPassword
}
});

return res.status(200).json({
message: 'Admin edited created'
});
} catch (error) {
console.log(error);
return res.status(500).json({
message: 'An error occurred while updating admin'
});
}
});

// Delete admin
router.delete('/delete/:id', accessValidation, async (req, res) => {
const { id } = req.params;

try {
await prisma.admin.delete({
where: {
admin_id: parseInt(id)
}
});

return res.status(200).json({
message: 'Admin deleted created'
});
} catch (error) {
console.log(error);
return res.status(500).json({
message: 'An error occurred while deleting admin'
});
}
});

export default router;

0 comments on commit 2545c10

Please sign in to comment.