From c59de0250ad49a858f034475319518812b1825fd Mon Sep 17 00:00:00 2001 From: Eric Fithian Date: Fri, 2 Feb 2024 23:31:38 -0700 Subject: [PATCH 1/6] events integration --- .vscode/settings.json | 7 +- backend/controllers/EventController.js | 39 +++-- backend/routes/AdminRouter.js | 5 + backend/routes/EventRouter.js | 3 + frontend/src/index.js | 11 +- frontend/src/objects/Event.js | 10 +- frontend/src/routes/event.jsx | 152 ++++++++++++++---- frontend/src/routes/events.jsx | 39 ++++- .../src/services/Events/EventsRepository.js | 57 +++++++ frontend/src/services/Events/EventsService.js | 64 ++++++++ .../services/MockServices/MockEventService.js | 20 +-- frontend/src/services/handleRegister.js | 2 +- sql-scripts/init.sql | 3 +- 13 files changed, 338 insertions(+), 74 deletions(-) create mode 100644 frontend/src/services/Events/EventsRepository.js create mode 100644 frontend/src/services/Events/EventsService.js diff --git a/.vscode/settings.json b/.vscode/settings.json index 9329ffb..420967f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,8 @@ { "editor.codeActionsOnSave": { - "source.fixAll.eslint": "explicit" + "source.fixAll.eslint": true }, - "editor.formatOnSave":false, - "css.lint.unknownAtRules":"ignore", + "eslint.validate": ["javascript, typescript, vue, html, css, scss, json, markdown"], + "editor.formatOnSave": true, + "css.lint.unknownAtRules": "ignore" } \ No newline at end of file diff --git a/backend/controllers/EventController.js b/backend/controllers/EventController.js index daeca2a..afd7f6e 100644 --- a/backend/controllers/EventController.js +++ b/backend/controllers/EventController.js @@ -35,13 +35,13 @@ const getEventById = async (req, res, next) => { }; const createEvent = async (req, res, next) => { - const {name, location, datetime, description, capacity} = req.body; + const {name, location, start_time, end_time, description, capacity} = req.body; try { const event = await db.one(` - INSERT INTO Events (name, location, datetime, description, vendor_capacity) - VALUES ($1, $2, $3, $4, $5) + INSERT INTO Events (name, location, start_time, end_time, description, vendor_capacity) + VALUES ($1, $2, $3, $4, $5, $6) RETURNING *; - `, [name, location, datetime, description, capacity]); + `, [name, location, start_time, end_time, description, capacity]); // Returns the created event res.locals.data = event; @@ -55,19 +55,20 @@ const createEvent = async (req, res, next) => { const updateEvent = async (req, res, next) => { const {event_id} = req.params; - const {name, location, datetime, description, capacity} = req.body; + const {name, location, start_time, end_time, description, capacity} = req.body; try { const result = await db.one(` UPDATE Events SET name = $1, location = $2, - datetime = $3, - description = $4, - vendor_capacity = $5 - WHERE event_id = $6 + start_time = $3, + end_time = $4, + description = $5, + vendor_capacity = $6 + WHERE event_id = $7 RETURNING *; - `, [name, location, datetime, description, capacity, event_id]); + `, [name, location, start_time, end_time, description, capacity, event_id]); if (!result) { return res.status(404).json({error: 'Event not found'}); @@ -81,4 +82,20 @@ const updateEvent = async (req, res, next) => { } }; -module.exports = {getAllEvents, getEventById, createEvent, updateEvent}; +const deleteEvent = async (req, res, next) => { + const {event_id} = req.params; + try { + const result = await db.oneOrNone('DELETE FROM Events WHERE event_id = $1 RETURNING *;', [event_id]); + if (!result) { + return res.status(404).json({error: 'Event not found'}); + } else { + res.locals.data = result; + next(); + } + } catch (error) { + console.error('Error deleting event:', error); + return res.status(500).json({error: 'Internal Server Error'}); + } +} + +module.exports = {getAllEvents, getEventById, createEvent, updateEvent, deleteEvent}; diff --git a/backend/routes/AdminRouter.js b/backend/routes/AdminRouter.js index eb1d174..f9b04d1 100644 --- a/backend/routes/AdminRouter.js +++ b/backend/routes/AdminRouter.js @@ -47,4 +47,9 @@ router.post('/login', getAdminByEmail, signAdminToken, (req, res) => { // res.status(200).json({status: 'success', admin: res.locals.data}); // }); +// DELETE ROUTE IN PRODUCTION -- CREATE AN ADMIN ACCOUNT FOR TESTING PURPOSES +router.post('/', createAdminMiddleware, (req, res) => { + res.status(200).json({status: 'success'}); +}); + module.exports = router; diff --git a/backend/routes/EventRouter.js b/backend/routes/EventRouter.js index 09f3cb2..c1a251a 100644 --- a/backend/routes/EventRouter.js +++ b/backend/routes/EventRouter.js @@ -5,6 +5,7 @@ const { getEventById, createEvent, updateEvent, + deleteEvent, } = require('../controllers/EventController'); const sendSuccessResponse = require('../middleware/successResponse'); const {verify} = require('../controllers/AuthController'); @@ -21,4 +22,6 @@ router.post('/', verify('admin'), createEvent, sendSuccessResponse); // Update an existing event router.put('/:event_id', verify('admin'), updateEvent, sendSuccessResponse); +router.delete('/:event_id', verify('admin'), deleteEvent, sendSuccessResponse); + module.exports = router; diff --git a/frontend/src/index.js b/frontend/src/index.js index e985932..1804be0 100644 --- a/frontend/src/index.js +++ b/frontend/src/index.js @@ -19,6 +19,7 @@ import MockEventService from './services/MockServices/MockEventService.js'; // import MockLoginService from './services/MockServices/MockLoginService'; import {handleLoginVendor} from './services/handleLogin.js'; import {handleRegister} from './services/handleRegister.js'; +import EventsService from './services/Events/EventsService.js'; import config from './config.js'; @@ -27,6 +28,12 @@ import {MessageProvider} from './context.jsx'; const isadmin = true; const session = true; +// base url for the backend +const baseUrl = 'http://localhost:3001'; + +// Initilize Services +const eventsService = new EventsService(baseUrl); + // Setup the mock vendor service if (config.environment === 'dev') { @@ -62,11 +69,11 @@ const router = createBrowserRouter([ }, { path: '/events/:eventId', - element: session ? : , + element: session ? : , }, { path: '/events', - element: session ? : , + element: session ? : , }, { path: '/vendors', diff --git a/frontend/src/objects/Event.js b/frontend/src/objects/Event.js index 4d9bc2a..188897a 100644 --- a/frontend/src/objects/Event.js +++ b/frontend/src/objects/Event.js @@ -2,17 +2,13 @@ Storage mechanism for a vendor object */ class Event { - constructor(eventId, name, location, datetime, description, vendorCapacity, durationHours = 2) { + constructor(eventId, name, location, startTime, endTime, description, vendorCapacity) { this.eventId = eventId; this.name = name; this.location = location; - this.date = datetime.toLocaleDateString(); - this.startTime = datetime.toLocaleTimeString(); - - // Create a new Date object for the end time - const endTime = new Date(datetime.getTime() + durationHours * 60 * 60 * 1000); + this.date = startTime.toLocaleDateString(); + this.startTime = startTime.toLocaleTimeString(); this.endTime = endTime.toLocaleTimeString(); - this.description = description; this.vendorCapacity = vendorCapacity; } diff --git a/frontend/src/routes/event.jsx b/frontend/src/routes/event.jsx index 057debd..5d37436 100644 --- a/frontend/src/routes/event.jsx +++ b/frontend/src/routes/event.jsx @@ -1,48 +1,51 @@ -import React, {useEffect} from 'react'; +import React, {useEffect, useState} from 'react'; import {useNavigate, useParams} from 'react-router-dom'; +import PropTypes from 'prop-types'; +import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; +import {faCaretDown, faAnglesLeft} from '@fortawesome/free-solid-svg-icons'; import logo from '../assets/PIM_logo_white.png'; import bLogo from '../assets/PIM_logo_black.png'; -import {useState} from 'react'; -import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; -import {faCaretDown} from '@fortawesome/free-solid-svg-icons'; -import {faAnglesLeft} from '@fortawesome/free-solid-svg-icons'; -import PropTypes from 'prop-types'; -// eventually have EventService.getEventById(useParams()) -// use params will get the params from the url -export default function Event({EventService}) { +export default function Event({eventsService}) { + const [event, setEvent] = useState(null); const [about, setAbout] = useState(false); - const [vendorOpen, setVendorOpen] = useState(false); const navigate = useNavigate(); const {eventId} = useParams(); - // const [register, setRegistered] = useState(false); - // wondering if I could use object destructuring here - // e.g const [location, setLocation] = useState({getEvent}) - // b/c getEvent realistically has a prop location - const e = EventService.getEvent(parseInt(eventId)); - console.log(EventService.getEvent(0)); - if (e === undefined) { - useEffect(()=>{ - navigate('/events'); - }); + useEffect(() => { + const fetchEvent = async () => { + const eventData = await eventsService.getEventById(parseInt(eventId)); + if (!eventData) { + navigate('/events'); + } else { + setEvent(eventData); + } + }; + + fetchEvent(); + }, [eventId, eventsService, navigate]); + + if (!event) { + return
Event Not Found
; } - const {name, location, date, startTime, endTime, description, vendorCapacity} = e !== undefined ? e : {name: 'Loading...', location: 'Loading...', date: 'Loading...', startTime: 'Loading...', endTime: 'Loading...', description: 'Loading...', vendorCapacity: 'Loading...'}; - // const vendorList = RegisterEventService[id].getVendors(); + + const {name, location, date, startTime, endTime, description} = event; const vendorImages = [logo, bLogo, logo, bLogo, logo, bLogo, logo, bLogo, logo, bLogo, logo, bLogo]; const toggleVendor = () => { - setVendorOpen(!vendorOpen); + setVendorOpen(!vendorOpen); // Ensure `vendorOpen` state is used properly }; async function handleRegister() { - // handle the user registering for the event - return; + // Handle the user registering for the event } + return ( -
- - +
+ + Event Logo
{name}
About
@@ -52,7 +55,7 @@ export default function Event({EventService}) { {description}
{location}
-
{date} | {startTime}
+
{date} | {startTime} - {endTime}
+ ); } -// -// put the images into a container, try to make it sideways scrollable where images are cutoff by border of div -// resize images - Event.propTypes = { - EventService: PropTypes.func.isRequired, + eventsService: PropTypes.shape({ + getEventById: PropTypes.func.isRequired, + }).isRequired, }; + +// import React, {useEffect} from 'react'; +// import {useNavigate, useParams} from 'react-router-dom'; +// import logo from '../assets/PIM_logo_white.png'; +// import bLogo from '../assets/PIM_logo_black.png'; +// import {useState} from 'react'; +// import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; +// import {faCaretDown} from '@fortawesome/free-solid-svg-icons'; +// import {faAnglesLeft} from '@fortawesome/free-solid-svg-icons'; +// import PropTypes from 'prop-types'; + +// // eventually have EventService.getEventById(useParams()) +// // use params will get the params from the url +// export default function Event({eventsService}) { +// const [about, setAbout] = useState(false); +// const [vendorOpen, setVendorOpen] = useState(false); +// const navigate = useNavigate(); +// const {eventId} = useParams(); + +// // const [register, setRegistered] = useState(false); +// // wondering if I could use object destructuring here +// // e.g const [location, setLocation] = useState({getEvent}) +// // b/c getEvent realistically has a prop location +// const e = eventsService.getEventById(parseInt(eventId)); +// console.log(eventsService.getEventById(0)); +// if (e === undefined) { +// useEffect(()=>{ +// navigate('/events'); +// }); +// } +// const {name, location, date, startTime, endTime, description, vendorCapacity} = e !== undefined ? e : {name: 'Loading...', location: 'Loading...', date: 'Loading...', startTime: 'Loading...', endTime: 'Loading...', description: 'Loading...', vendorCapacity: 'Loading...'}; +// // const vendorList = RegisterEventService[id].getVendors(); +// const vendorImages = [logo, bLogo, logo, bLogo, logo, bLogo, logo, bLogo, logo, bLogo, logo, bLogo]; + +// const toggleVendor = () => { +// setVendorOpen(!vendorOpen); +// }; + +// async function handleRegister() { +// // handle the user registering for the event +// return; +// } +// return ( +//
+// +// +//
{name}
+//
+//
About
+// +//
+//
+// {description} +//
+//
{location}
+//
{date} | {startTime}
+// +//
+//
Attending Vendors
+//
+// {vendorImages.map((vendorImg) => ( +// {vendorImg} +// ))} +//
+//
+// ); +// } + +// // +// // put the images into a container, try to make it sideways scrollable where images are cutoff by border of div +// // resize images + +// Events.propTypes = { +// eventsService: PropTypes.shape({ +// getEventById: PropTypes.func.isRequired, +// }).isRequired, +// }; + + diff --git a/frontend/src/routes/events.jsx b/frontend/src/routes/events.jsx index a1d3183..335e64e 100644 --- a/frontend/src/routes/events.jsx +++ b/frontend/src/routes/events.jsx @@ -1,13 +1,32 @@ import React from 'react'; -import {useState} from 'react'; +import {useState, useEffect} from 'react'; import PropTypes from 'prop-types'; -export default function Events({EventService}) { - const [events] = useState(EventService.getEvents()); +export default function Events({eventsService}) { + const [events, setEvents] = useState([]); + const [error, setError] = useState(''); + + useEffect(() => { + const fetchEvents = async () => { + try { + const fetchedEvents = await eventsService.getAllEvents(); + if (fetchedEvents.length === 0) { + setError('There are currently no events.'); + } else { + setEvents(fetchedEvents); + setError(''); // Reset error state if events are fetched successfully + } + } catch (error) { + console.error('Error fetching events:', error); + setError('Failed to fetch events.'); // Handle any other errors during fetch + } + }; + + fetchEvents(); + }, [eventsService]); const eventDisplay = (event) => ( - // event name, date, starttime, endtime, description, location in a single row
{event.name}
@@ -23,6 +42,14 @@ export default function Events({EventService}) {
); + if (error) { + return ( +
+

No Events Found

+
+ ); + } + return ( // display in a single column
@@ -39,5 +66,7 @@ export default function Events({EventService}) { } Events.propTypes = { - EventService: PropTypes.func.isRequired, + eventsService: PropTypes.shape({ + getAllEvents: PropTypes.func.isRequired, + }).isRequired, }; diff --git a/frontend/src/services/Events/EventsRepository.js b/frontend/src/services/Events/EventsRepository.js new file mode 100644 index 0000000..ee9c193 --- /dev/null +++ b/frontend/src/services/Events/EventsRepository.js @@ -0,0 +1,57 @@ +import axios from 'axios'; + +export default class EventsRepository { + constructor(baseUrl) { + this.baseUrl = baseUrl; + } + + async getAllEvents() { + try { + const response = await axios.get(`${this.baseUrl}/events`); + return response.data; + } catch (error) { + console.error('Error fetching events:', error); + throw error; + } + } + + async getEventById(eventId) { + try { + const response = await axios.get(`${this.baseUrl}/events/${eventId}`); + return response.data; + } catch (error) { + console.error(`Error fetching event with ID ${eventId}:`, error); + throw error; + } + } + + async createEvent(eventData) { + try { + const response = await axios.post(`${this.baseUrl}/events`, eventData); + return response.data; + } catch (error) { + console.error('Error creating event:', error); + throw error; + } + } + + async updateEvent(eventId, eventData) { + try { + const response = await axios.put(`${this.baseUrl}/events/${eventId}`, eventData); + return response.data; + } catch (error) { + console.error(`Error updating event with ID ${eventId}:`, error); + throw error; + } + } + + async deleteEvent(eventId) { + try { + const response = await axios.delete(`${this.baseUrl}/events/${eventId}`); + return response.data; + } catch (error) { + console.error(`Error deleting event with ID ${eventId}:`, error); + throw error; + } + } +} diff --git a/frontend/src/services/Events/EventsService.js b/frontend/src/services/Events/EventsService.js new file mode 100644 index 0000000..39672b1 --- /dev/null +++ b/frontend/src/services/Events/EventsService.js @@ -0,0 +1,64 @@ +import EventsRepository from './EventsRepository'; +import Event from '../../objects/Event'; + +export default class EventsService { + constructor(baseUrl) { + this.eventsRepository = new EventsRepository(baseUrl); + } + + async getAllEvents() { + const eventsData = await this.eventsRepository.getAllEvents(); + return eventsData.map((data) => new Event( + data.eventId, + data.name, + data.location, + new Date(data.start_time), + new Date(data.end_time), + data.description, + data.vendor_capacity, + )); + } + + async getEventById(eventId) { + const eventData = await this.eventsRepository.getEventById(eventId); + return new Event( + eventData.eventId, + eventData.name, + eventData.location, + new Date(eventData.start_time), + new Date(eventData.end_time), + eventData.description, + eventData.vendorCapacity, + ); + } + + async createEvent(event) { + const eventData = { + // Assuming your Event class has properties that directly map to your data structure + name: event.name, + location: event.location, + start_time: event.start_time.toISOString(), // Convert Date object to string + end_time: event.end_time.toISOString(), + description: event.description, + vendorCapacity: event.vendorCapacity, + // Include other properties as needed + }; + return await this.eventsRepository.createEvent(eventData); + } + + async updateEvent(event) { + const eventData = { + name: event.name, + location: event.location, + start_time: event.start_time.toISOString(), + end_time: event.end_time.toISOString(), + description: event.description, + vendorCapacity: event.vendorCapacity, + }; + return await this.eventsRepository.updateEvent(event.eventId, eventData); + } + + async deleteEvent(eventId) { + return await this.eventsRepository.deleteEvent(eventId); + } +} diff --git a/frontend/src/services/MockServices/MockEventService.js b/frontend/src/services/MockServices/MockEventService.js index 2153d14..8339230 100644 --- a/frontend/src/services/MockServices/MockEventService.js +++ b/frontend/src/services/MockServices/MockEventService.js @@ -6,16 +6,16 @@ export default class MockEventService { static init() { if (this.mockEvents === undefined || this.mockEvents.length === 0) { this.mockEvents = [ - new Event(1, 'Music Festival', 'Central Park, NY', new Date(2023, 5, 20, 16, 0), 'A festival of music and arts.', 50, 4), - new Event(2, 'Tech Conference', 'Convention Center, SF', new Date(2023, 6, 15, 9, 0), 'A conference for tech enthusiasts.', 100, 8), - new Event(3, 'Food Fair', 'Downtown, LA', new Date(2023, 7, 10, 11, 0), 'A fair showcasing local food vendors.', 30, 3), - new Event(4, 'Book Expo', 'Library, Boston', new Date(2023, 8, 5, 10, 0), 'An expo for book lovers.', 40, 5), - new Event(5, 'Film Festival', 'Cinema, Austin', new Date(2023, 9, 1, 13, 0), 'A festival showcasing independent films.', 60, 6), - new Event(6, 'Art Exhibition', 'Museum, Chicago', new Date(2023, 10, 25, 14, 0), 'An exhibition of contemporary art.', 20, 2), - new Event(7, 'Craft Market', 'Town Square, Portland', new Date(2023, 11, 20, 10, 0), 'A market for local crafts.', 35, 4), - new Event(8, 'Comedy Night', 'Theater, Seattle', new Date(2023, 0, 15, 20, 0), 'A night of stand-up comedy.', 15, 3), - new Event(9, 'Poetry Reading', 'Cafe, Denver', new Date(2023, 1, 10, 19, 0), 'A reading by local poets.', 10, 2), - new Event(10, 'Dance Workshop', 'Studio, Miami', new Date(2023, 2, 7, 18, 0), 'A workshop for dance enthusiasts.', 25, 3), + new Event(1, 'Music Festival', 'Central Park, NY', new Date(2023, 5, 20, 16, 0), new Date(2023, 5, 20, 18, 0), 'A festival of music and arts.', 50), + new Event(2, 'Tech Conference', 'Convention Center, SF', new Date(2023, 6, 15, 9, 0), new Date(2023, 6, 15, 11, 0), 'A conference for tech enthusiasts.', 100), + new Event(3, 'Food Fair', 'Downtown, LA', new Date(2023, 7, 10, 11, 0), new Date(2023, 7, 10, 13, 0), 'A fair showcasing local food vendors.', 30), + new Event(4, 'Book Expo', 'Library, Boston', new Date(2023, 8, 5, 10, 0), new Date(2023, 8, 5, 12, 0), 'An expo for book lovers.', 40), + new Event(5, 'Film Festival', 'Cinema, Austin', new Date(2023, 9, 1, 13, 0), new Date(2023, 9, 1, 15, 0), 'A festival showcasing independent films.', 60), + new Event(6, 'Art Exhibition', 'Museum, Chicago', new Date(2023, 10, 25, 14, 0), new Date(2023, 10, 25, 16, 0), 'An exhibition of contemporary art.', 20), + new Event(7, 'Craft Market', 'Town Square, Portland', new Date(2023, 11, 20, 10, 0), new Date(2023, 11, 20, 12, 0), 'A market for local crafts.', 35), + new Event(8, 'Comedy Night', 'Theater, Seattle', new Date(2023, 0, 15, 20, 0), new Date(2023, 0, 15, 22, 0), 'A night of stand-up comedy.', 15), + new Event(9, 'Poetry Reading', 'Cafe, Denver', new Date(2023, 1, 10, 19, 0), new Date(2023, 1, 10, 21, 0), 'A reading by local poets.', 10), + new Event(10, 'Dance Workshop', 'Studio, Miami', new Date(2023, 2, 7, 18, 0), new Date(2023, 2, 7, 20, 0), 'A workshop for dance enthusiasts.', 25), ]; } } diff --git a/frontend/src/services/handleRegister.js b/frontend/src/services/handleRegister.js index a794184..2955824 100644 --- a/frontend/src/services/handleRegister.js +++ b/frontend/src/services/handleRegister.js @@ -1,6 +1,6 @@ import axios from 'axios'; // function that returns a boolean, true if the registration was successful, false otherwise. -export default async function handleRegister(data) { +export async function handleRegister(data) { const server = axios.create({ baseURL: 'http://localhost:3001', withCredentials: false, diff --git a/sql-scripts/init.sql b/sql-scripts/init.sql index f7d4f0f..c4474f4 100644 --- a/sql-scripts/init.sql +++ b/sql-scripts/init.sql @@ -23,7 +23,8 @@ CREATE TABLE Events ( event_id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, location VARCHAR(255), - datetime TIMESTAMP NOT NULL, + start_time TIMESTAMP NOT NULL, + end_time TIMESTAMP NOT NULL, description TEXT, vendor_capacity INT NOT NULL ); From b27271bb9099b08d0a24fb45b33d58ecbc48c08f Mon Sep 17 00:00:00 2001 From: nh602 Date: Sat, 3 Feb 2024 23:27:31 +0000 Subject: [PATCH 2/6] Moved baseUrl into config file and dynamically load services based on config.environment --- frontend/src/config.js | 1 + frontend/src/index.js | 59 +++++++++++++++++++++++++----------------- 2 files changed, 36 insertions(+), 24 deletions(-) diff --git a/frontend/src/config.js b/frontend/src/config.js index 3538cb2..f034e08 100644 --- a/frontend/src/config.js +++ b/frontend/src/config.js @@ -1,5 +1,6 @@ const config = { environment: 'dev', + baseUrl: 'http://localhost:3001', }; export default config; diff --git a/frontend/src/index.js b/frontend/src/index.js index fe488da..197ba71 100644 --- a/frontend/src/index.js +++ b/frontend/src/index.js @@ -10,83 +10,94 @@ import reportWebVitals from './reportWebVitals'; import Vendors from './routes/vendors.jsx'; import ErrorPage from './components/error.jsx'; import './App.css'; -import {createBrowserRouter, Navigate, RouterProvider} from 'react-router-dom'; +import { createBrowserRouter, Navigate, RouterProvider } from 'react-router-dom'; import Register from './routes/register'; import MockEventService from './services/MockServices/MockEventService.js'; import MockVendorService from './services/MockServices/MockVendorService.js'; import ResetPassword from './routes/reset_password'; -import {handleLoginVendor} from './services/handleLogin.js'; -import {handleRegister} from './services/handleRegister.js'; +import { handleLoginVendor } from './services/handleLogin.js'; +import { handleRegister } from './services/handleRegister.js'; import EventsService from './services/Events/EventsService.js'; import config from './config.js'; -import {MessageProvider} from './context.jsx'; +import { MessageProvider } from './context.jsx'; const isadmin = true; const session = true; -// base url for the backend -const baseUrl = 'http://localhost:3001'; - -// Initilize Services -const eventsService = new EventsService(baseUrl); +// Load environment from config +const environment = config.environment; +let eventService; +let vendorService; // Setup the mock vendor service if (config.environment === 'dev') { MockVendorService.init(); MockEventService.init(); + + eventService = MockEventService; + vendorService = MockVendorService; +} else if (config.environment === 'prod') { + // Load base url for the backend + const baseUrl = config.baseUrl; + + // Initilize Services + const eventsService = new EventsService(baseUrl); + + eventService = eventsService; + vendorService = vendorService; } const router = createBrowserRouter([ { path: '/', // loader: loaderfunc(), - element: , + element: , children: [ { path: '/vendors/:vendorId', - element: session? : , + element: session ? : , }, { path: '/login', - element: , + element: , }, { path: '/register', - element: , + element: , }, { path: '/reset_password', - element: , + element: , }, { path: '/profile', - element: session ? : , + element: session ? : , }, { path: '/events/:eventId', - element: session ? : , + element: session ? : , }, { path: '/events', - element: session ? : , + element: session ? : , }, { path: '/vendors', - element: session && isadmin? : , + element: session && isadmin ? : , }], - errorElement: , + errorElement: , }, ]); const root = ReactDOM.createRoot(document.getElementById('root')); export default root.render( - - - - - , + + + + + , ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) From 9a55e123f59c8bb47bdfed4ff8591627877aee88 Mon Sep 17 00:00:00 2001 From: nh602 Date: Wed, 7 Feb 2024 20:29:19 +0000 Subject: [PATCH 3/6] Backend routes no longer overlap with frontend routes by prepending /api --- backend/index.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/backend/index.js b/backend/index.js index f3873df..3b52c27 100644 --- a/backend/index.js +++ b/backend/index.js @@ -14,7 +14,7 @@ const app = express(); app.use(express.json()); const errorHandler = require('errorhandler'); -app.use(errorHandler({dumbExceptions: true, showStack: true})); +app.use(errorHandler({ dumbExceptions: true, showStack: true })); // Allows cross origin requests const cors = require('cors'); @@ -29,9 +29,10 @@ const VendorRouter = require('./routes/VendorRouter'); const AdminRouter = require('./routes/AdminRouter'); const EventRouter = require('./routes/EventRouter'); -app.use('/vendors', VendorRouter); -app.use('/events', EventRouter); -app.use('/admins', AdminRouter); +// Routes overlapped with the frontend +app.use('/api/vendors', VendorRouter); +app.use('/api/events', EventRouter); +app.use('/api/admins', AdminRouter); app.get('/', (req, res) => { res.status(202).send('Hello World!'); From c567c60649aa84e8f2560286e75640591d94f792 Mon Sep 17 00:00:00 2001 From: nh602 Date: Wed, 7 Feb 2024 20:30:44 +0000 Subject: [PATCH 4/6] Fixed string comparison bug for loading dev services --- frontend/src/index.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/frontend/src/index.js b/frontend/src/index.js index 197ba71..086e5f2 100644 --- a/frontend/src/index.js +++ b/frontend/src/index.js @@ -25,20 +25,17 @@ import { MessageProvider } from './context.jsx'; const isadmin = true; const session = true; -// Load environment from config -const environment = config.environment; - let eventService; let vendorService; // Setup the mock vendor service -if (config.environment === 'dev') { +if (config.environment == 'dev') { MockVendorService.init(); MockEventService.init(); eventService = MockEventService; vendorService = MockVendorService; -} else if (config.environment === 'prod') { +} else if (config.environment == 'prod') { // Load base url for the backend const baseUrl = config.baseUrl; From dfd8dcbe10dbea01851acf775c8c98d5c06cb74f Mon Sep 17 00:00:00 2001 From: nh602 Date: Wed, 7 Feb 2024 20:31:09 +0000 Subject: [PATCH 5/6] Changed method signature so that real and mock event services have same interface. --- frontend/src/services/MockServices/MockEventService.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/services/MockServices/MockEventService.js b/frontend/src/services/MockServices/MockEventService.js index 8339230..2019d4d 100644 --- a/frontend/src/services/MockServices/MockEventService.js +++ b/frontend/src/services/MockServices/MockEventService.js @@ -20,7 +20,7 @@ export default class MockEventService { } } - static getEvents() { + static getAllEvents() { return this.mockEvents; } From 87721335c0675670eb52c7cdf236f7e4cb316b48 Mon Sep 17 00:00:00 2001 From: nh602 Date: Wed, 7 Feb 2024 20:32:55 +0000 Subject: [PATCH 6/6] Appended /api to baseurl to match backend changes --- frontend/src/config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/config.js b/frontend/src/config.js index f034e08..0eac2e3 100644 --- a/frontend/src/config.js +++ b/frontend/src/config.js @@ -1,6 +1,6 @@ const config = { environment: 'dev', - baseUrl: 'http://localhost:3001', + baseUrl: 'http://localhost:3001/api', }; export default config;