diff --git a/Backend/src/models/pricealarms/pricealarms.router.ts b/Backend/src/models/pricealarms/pricealarms.router.ts index 4e0e014..469c1c5 100644 --- a/Backend/src/models/pricealarms/pricealarms.router.ts +++ b/Backend/src/models/pricealarms/pricealarms.router.ts @@ -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.'})); } }); + +// 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.'})); + } +}); diff --git a/Backend/src/models/pricealarms/pricealarms.service.ts b/Backend/src/models/pricealarms/pricealarms.service.ts index ef44db6..279b05b 100644 --- a/Backend/src/models/pricealarms/pricealarms.service.ts +++ b/Backend/src/models/pricealarms/pricealarms.service.ts @@ -76,3 +76,31 @@ export const getPriceAlarms = async (user_id: number): Promise => { } } }; + +/** + * 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 => { + 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; +};