From 83c9d090e1dddb2b9f3a4a40b9e12bc8a0fac4be Mon Sep 17 00:00:00 2001 From: Patrick Mueller Date: Sun, 25 Dec 2022 15:38:13 +0100 Subject: [PATCH] Add methods to insert, update and delete events --- src/models/calendar/events/events.router.ts | 113 ++++++++++++++++++- src/models/calendar/events/events.service.ts | 45 +++++++- 2 files changed, 153 insertions(+), 5 deletions(-) diff --git a/src/models/calendar/events/events.router.ts b/src/models/calendar/events/events.router.ts index ea8c00b..a18e6c1 100644 --- a/src/models/calendar/events/events.router.ts +++ b/src/models/calendar/events/events.router.ts @@ -3,6 +3,7 @@ */ import express, {Request, Response} from 'express'; +import {Event} from './event.interface'; import * as EventService from './events.service'; import * as iCalService from './icalgenerator.service'; import * as CredentialService from './credentials.service'; @@ -19,7 +20,7 @@ export const eventsRouter = express.Router(); /** * Constants */ -export const calendarNames = new Map ([ +export const calendarNames = new Map([ ['public', {id: 1, name: 'Nachklang_calendar'}], ['members', {id: 2, name: 'Nachklang_internal_calendar'}], ['management', {id: 3, name: 'Nachklang_management_calendar'}] @@ -41,7 +42,7 @@ eventsRouter.get('/:calendar/json', async (req: Request, res: Response) => { return; } - if(!Array.from(calendarNames.keys()).includes(calendarName)) { + if (!Array.from(calendarNames.keys()).includes(calendarName)) { res.status(401).send({'message': 'Unknown calendar.'}); return; } @@ -75,7 +76,7 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => { return; } - if(!Array.from(calendarNames.keys()).includes(calendarName)) { + if (!Array.from(calendarNames.keys()).includes(calendarName)) { res.status(401).send({'message': 'Unknown calendar.'}); return; } @@ -107,3 +108,109 @@ eventsRouter.get('/:calendar/ical', async (req: Request, res: Response) => { }); } }); + +eventsRouter.post('/', async (req: Request, res: Response) => { + try { + // Get params + let password = req.body.password; + + if (!CredentialService.checkAdminPrivileges(password)) { + res.status(403).send({'message': 'Insufficient privileges.'}); + return; + } + + if ( + req.body.calendarId === undefined || + isNullOrBlank(req.body.name) || + req.body.startDateTime === undefined || + req.body.endDateTime === undefined + ) { + res.status(401).send({'message': 'Required parameters missing'}); + return; + } + + let event: Event = { + event_id: -1, + calendar_id: req.body.calendarId, + uuid: '', + name: req.body.name, + description: req.body.description ?? '', + start_datetime: new Date(req.body.startDateTime), + end_datetime: new Date(req.body.endDateTime), + created_date: new Date(), + location: req.body.location ?? '', + created_by: req.body.createdBy ?? '', + url: req.body.url ?? '' + }; + + let eventId = await EventService.createEvent(event); + + res.status(201).send({'message': 'Event with id ' + eventId + ' was created successfully.'}); + } catch (e: any) { + let errorGuid = Guid.create().toString(); + logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); + res.status(500).send({ + 'status': 'PROCESSING_ERROR', + 'message': 'Internal Server Error. Try again later.', + 'reference': errorGuid + }); + } +}); + +eventsRouter.put('/:eventId', async (req: Request, res: Response) => { + try { + // Get params + let password = req.body.password; + + if (!CredentialService.checkAdminPrivileges(password)) { + res.status(403).send({'message': 'Insufficient privileges.'}); + return; + } + + if ( + req.params.eventId === undefined || + req.body.calendarId === undefined || + isNullOrBlank(req.body.name) || + req.body.startDateTime === undefined || + req.body.endDateTime === undefined + ) { + res.status(401).send({'message': 'Required parameters missing'}); + return; + } + + let event: Event = { + event_id: parseInt(req.params.eventId, 10), + calendar_id: req.body.calendarId, + uuid: '', + name: req.body.name, + description: req.body.description ?? '', + start_datetime: new Date(req.body.startDateTime), + end_datetime: new Date(req.body.endDateTime), + created_date: new Date(), + location: req.body.location ?? '', + created_by: req.body.createdBy ?? '', + url: req.body.url ?? '' + }; + + let success = await EventService.updateEvent(event); + + + res.status(200).send({'message': 'Event was successfully updated'}); + } catch (e: any) { + let errorGuid = Guid.create().toString(); + logger.error('Error handling a request: ' + e.message, {reference: errorGuid}); + res.status(500).send({ + 'status': 'PROCESSING_ERROR', + 'message': 'Internal Server Error. Try again later.', + 'reference': errorGuid + }); + } +}); + +/** + * Checks if a given string is null, undefined or blank + * @param str The string to check + */ +function isNullOrBlank(str: string | null): boolean { + return str === null || str === undefined || str.trim() === ''; +} diff --git a/src/models/calendar/events/events.service.ts b/src/models/calendar/events/events.service.ts index 185bee4..d422482 100644 --- a/src/models/calendar/events/events.service.ts +++ b/src/models/calendar/events/events.service.ts @@ -1,5 +1,4 @@ import * as dotenv from 'dotenv'; -import * as bcrypt from 'bcrypt'; import {Guid} from 'guid-typescript'; import {Event} from './event.interface'; import {NachklangCalendarDB} from '../Calendar.db'; @@ -18,7 +17,7 @@ export const getAllEvents = async (calendarId: number): Promise => { const eventsQuery = 'SELECT * FROM events WHERE calendar_id = ?'; const eventsRes = await conn.query(eventsQuery, calendarId); - for(let row of eventsRes) { + for (let row of eventsRes) { eventRows.push(row); } @@ -30,3 +29,45 @@ export const getAllEvents = async (calendarId: number): Promise => { await conn.end(); } }; + +/** + * Create the given event in the database + * @param event The event to create + */ +export const createEvent = async (event: Event): Promise => { + let conn = await NachklangCalendarDB.getConnection(); + try { + let eventUUID = Guid.create().toString(); + const eventsQuery = 'INSERT INTO events (calendar_id, uuid, name, description, start_datetime, end_datetime, location, created_by, url) VALUES (?,?,?,?,?,?,?,?,?) RETURNING event_id'; + const eventsRes = await conn.query(eventsQuery, [event.calendar_id, eventUUID, event.name, event.description, event.start_datetime, event.end_datetime, event.location, event.created_by, event.url]); + + return eventsRes[0].event_id; + } catch (err) { + throw err; + } finally { + // Return connection + await conn.end(); + } +}; + +/** + * Update the given event in the database + * @param event The event to update + */ +export const updateEvent = async (event: Event): Promise => { + let conn = await NachklangCalendarDB.getConnection(); + try { + let eventUUID = Guid.create().toString(); + const eventsQuery = 'UPDATE events SET name = ?, description = ?, start_datetime = ?, end_datetime = ?, location = ?, created_by = ?, url = ? WHERE event_id = ?'; + const eventsRes = await conn.query(eventsQuery, [event.name, event.description, event.start_datetime, event.end_datetime, event.location, event.created_by, event.url, event.event_id]); + + console.log(eventsRes); + + return eventsRes.affectedRows === 1; + } catch (err) { + throw err; + } finally { + // Return connection + await conn.end(); + } +};