I am a working on a personal project, and am still learning. I am building a REST API backend app with 3 models (User, Event, & City).
For a GET route I want to be able to
- list All events
- filter events by user
- filter events by city
I am uncertain what would be considered best practice for routes 2 & 3.
Currently, I have it routed through api/v1/events and the user has an option to add either the user_id OR the city_id to the params, and then my controller will pass the request to the correct service. I feel that there is a lot of room for user error here and want to improve it. I can think of a few different pathways forward but wanted to ask if there is a best practice for this.
Side note: to get the events filtered by users, I have to do a query to my User db, not the Event db. I am not sure if it looks wrong here and if I should move it to the User controller.
I have looked at a lot of API GitHub examples while building this but have not come across this specific situation. Thank you very much for your thoughts and insight.
My Controller func:
async function listAllEvents(req: express.Request, res: express.Response) {
logger.debug(`Entering GET All CONTROLLER - events/ endpoint.`);
type ReturnValue = User | Event[];
let events: ReturnValue = [];
if (req.query.cityId) {
let cityId = req.query.cityId as string;
events = await EventService.filterEventsByCityId(cityId);
} else if (req.query.userId) {
let userId = req.query.userId as string;
events = await EventService.filterEventsByUserId(userId);
} else {
events = await EventService.listAllEvents();
}
try {
if (!events) {
res.status(404).json({ error: `No events found` });
return;
} else {
res.json(events);
}
} catch (err) {
logger.error(err);
res.status(500).send(err);
}
}
Tamara Dowis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.