backend/api/routes/accountRoute.js

107 lines
2.5 KiB
JavaScript
Raw Normal View History

2020-05-07 12:14:13 +00:00
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
2020-05-01 15:32:46 +00:00
const { saltingRounds } = require('../../config/config');
const { authenticate } = require('../../middlewares/authenticate');
const { validateAccountID } = require('../../middlewares/validateAccountID');
2020-05-10 22:03:48 +00:00
const Account = require('../models/accountModel');
2020-05-01 15:32:46 +00:00
// TODO : remove if unused
2020-05-01 15:32:46 +00:00
router.post('/', async (req, res) => {
const data = { ...req.body };
const hash = bcrypt.hashSync(data.password, saltingRounds);
2020-05-07 12:14:13 +00:00
data.password = hash;
2020-05-01 15:32:46 +00:00
try {
const [account] = await Account.addAccount(data);
res.status(201).json(account);
2020-05-01 16:24:59 +00:00
} 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) {
2020-05-06 10:30:32 +00:00
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);
2020-05-06 10:30:32 +00:00
res.status(200).json({
message: `Account with id ${id} successfully deleted.`,
});
} catch (error) {
2020-05-06 10:30:32 +00:00
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,
2020-05-10 22:03:48 +00:00
});
}
},
);
2020-05-10 22:03:48 +00:00
router.get('/:id', authenticate, async (req, res) => {
const { id } = req.params;
try {
const account = await Account.getAccountById(id);
2020-05-10 22:03:48 +00:00
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({
2020-05-10 22:03:48 +00:00
message: `Failed to fetch account with id ${id}.`,
error,
});
}
});
2020-05-01 15:32:46 +00:00
module.exports = router;