BETTERZON-92: Adding API endpoint to edit (update) price alarms (#44)

This commit is contained in:
Patrick 2021-05-13 00:48:56 +02:00 committed by GitHub
parent cd0c11dbc7
commit 0be394fc1d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 70 additions and 0 deletions

View File

@ -85,3 +85,45 @@ pricealarmsRouter.post('/create', async (req: Request, res: Response) => {
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
} }
}); });
// PUT pricealarms/update
pricealarmsRouter.put('/update', async (req: Request, res: Response) => {
try {
// Authenticate user
const session_id = req.body.session_id;
const session_key = req.body.session_key;
const user_ip = req.connection.remoteAddress ?? '';
if (!session_id || !session_key) {
// Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return;
}
const user = await UserService.checkSession(session_id, session_key, user_ip);
// Get info for price alarm creation
const alarm_id = req.body.alarm_id;
const defined_price = req.body.defined_price;
if (!alarm_id || !defined_price) {
// Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return;
}
// Create price alarm
const success = await PriceAlarmsService.updatePriceAlarm(alarm_id, user.user_id, defined_price);
if (success) {
res.status(201).send(JSON.stringify({success: true}));
return;
} else {
res.status(500).send(JSON.stringify({success: false}));
return;
}
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
});

View File

@ -76,3 +76,31 @@ export const getPriceAlarms = async (user_id: number): Promise<PriceAlarms> => {
} }
} }
}; };
/**
* Updates the given price alarm with the given fields
* @param alarm_id The id of the price alarm to update
* @param user_id The id of the user that wants to update the price alarm
* @param defined_price The defined price for the price alarm
*/
export const updatePriceAlarm = async (alarm_id: number, user_id: number, defined_price: number): Promise<Boolean> => {
let conn;
try {
conn = await pool.getConnection();
const res = await conn.query('UPDATE price_alarms SET defined_price = ? WHERE alarm_id = ? AND user_id = ?', [defined_price, alarm_id, user_id]);
if (res.affectedRows === 1) {
return true;
} else {
return false;
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return false;
};