From b6f7fa42ea803e0b7463ec209a88c79c2efac857 Mon Sep 17 00:00:00 2001 From: huijieliu8 <91745551+metaphor987@users.noreply.github.com> Date: Fri, 29 Nov 2024 11:46:18 -0800 Subject: [PATCH] fix: get categories --- src/controllers/jobsController.js | 18 ++++++++++++++++-- src/routes/jobsRouter.js | 1 + 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/controllers/jobsController.js b/src/controllers/jobsController.js index f782e0eeb..65cfeafdc 100644 --- a/src/controllers/jobsController.js +++ b/src/controllers/jobsController.js @@ -56,8 +56,7 @@ const getJobById = async (req, res) => { // Controller to create a new job const createJob = async (req, res) => { - const { title, category, description, imageUrl, location, applyLink, jobDetailsLink } = - req.body; + const { title, category, description, imageUrl, location, applyLink, jobDetailsLink } = req.body; try { const newJob = new Job({ @@ -107,6 +106,20 @@ const deleteJob = async (req, res) => { } }; +const getCategories = async (req, res) => { + try { + const categories = await Job.distinct('category', {}); + + // Sort categories alphabetically + categories.sort((a, b) => a.localeCompare(b)); + + res.status(200).json({ categories }); + } catch (error) { + console.error('Error fetching categories:', error); + res.status(500).json({ message: 'Failed to fetch categories' }); + } +}; + // Export controllers as a plain object module.exports = { getJobs, @@ -114,4 +127,5 @@ module.exports = { createJob, updateJob, deleteJob, + getCategories, }; diff --git a/src/routes/jobsRouter.js b/src/routes/jobsRouter.js index 6dfa69a85..5b66735a6 100644 --- a/src/routes/jobsRouter.js +++ b/src/routes/jobsRouter.js @@ -5,6 +5,7 @@ const router = express.Router(); // Define routes router.get('/', jobsController.getJobs); +router.get('/categories', jobsController.getCategories); router.get('/:id', jobsController.getJobById); router.post('/', jobsController.createJob); router.put('/:id', jobsController.updateJob);