backend/api/routes/accountRoute.js

107 lines
2.5 KiB
JavaScript

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const { saltingRounds } = require('../../config/config');
const { authenticate } = require('../../middlewares/authenticate');
const { validateAccountID } = require('../../middlewares/validateAccountID');
const Account = require('../models/accountModel');
// TODO : remove if unused
router.post('/', async (req, res) => {
const data = { ...req.body };
const hash = bcrypt.hashSync(data.password, saltingRounds);
data.password = hash;
try {
const [account] = await Account.addAccount(data);
res.status(201).json(account);
} catch (error) {
res.status(500).json({ message: 'Failed to add new account.', error });
}
});
router.put('/:id', authenticate, validateAccountID, async (req, res) => {
const data = { ...req.body };
const { id } = req.params;
if (data.password) {
const hash = bcrypt.hashSync(data.password, 10);
data.password = hash;
}
try {
const account = await Account.updateAccount(data, id);
res.status(200).json(...account);
} catch (error) {
res.status(500).json({
message: `Failed to update account with id ${id}.`,
error,
});
}
});
router.delete('/:id', authenticate, validateAccountID, async (req, res) => {
const { id } = req.params;
try {
const account = await Account.deleteAccount(id);
res.status(200).json({
message: `Account with id ${id} successfully deleted.`,
});
} catch (error) {
res.status(500).json({
message: `Failed to delete account with id ${id}.`,
error,
});
}
});
router.get(
'/:id/meetings',
authenticate,
validateAccountID,
async (req, res) => {
const { id } = req.params;
try {
const meetings = await Account.getMeetingsByAccountId(id);
if (meetings.length == 0) {
res.status(200).json({
message: `There are no meetings for account with id ${id}.`,
});
} else {
res.status(200).json(meetings);
}
} catch (error) {
res.status(500).json({
message: `Failed to fetch meetings with account id ${id}.`,
error,
});
}
},
);
router.get('/:id', authenticate, async (req, res) => {
const { id } = req.params;
try {
const account = await Account.getAccountById(id);
if (typeof account == 'undefined') {
res.status(404).json({
message: `Account with id ${id} doesn't exist.`,
});
} else {
res.status(200).json(account);
}
} catch (error) {
res.status(500).json({
message: `Failed to fetch account with id ${id}.`,
error,
});
}
});
module.exports = router;