From 80da6870d27b171fdd339aacf9ab8bfa0253f4f9 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Wed, 5 Feb 2025 11:24:10 +0530 Subject: [PATCH] department names by city --- src/controllers/departmentController.js | 46 ++++++++++++++++++++++++- src/routes/departmentRoute.js | 19 ++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/controllers/departmentController.js b/src/controllers/departmentController.js index 7343f0bc..55d75b10 100644 --- a/src/controllers/departmentController.js +++ b/src/controllers/departmentController.js @@ -1078,4 +1078,48 @@ exports.getZonebasedLocations = async (req, reply) => { reply.send({ error: err.message }); } }; - \ No newline at end of file + + + // Helper function to fetch department names by city + const getDepartmentNamesByCity = async (city) => { + try { + const trimmedCity = city.trim(); + + // Allow for extra whitespace before or after the city value in the database + const query = { + city: { $regex: `^\\s*${trimmedCity}\\s*$`, $options: "i" } + }; + console.log("MongoDB Query:", JSON.stringify(query, null, 2)); + + const result = await Deparments.find(query) + .select("departmentName -_id") + .lean(); + + return result.map(doc => doc.departmentName); + } catch (error) { + console.error("Error fetching departments by city:", error); + throw new Error("Error fetching departments by city."); + } + }; + + +// API route handler +exports.getDepartmentsByCity = async (req, reply) => { + try { + const { city } = req.params; + if (!city || city.trim() === "") { + return reply.status(400).send({ message: "City is required." }); + } + + const departmentNames = await getDepartmentNamesByCity(city); + + if (departmentNames.length === 0) { + return reply.status(404).send({ message: "No departments found for the specified city." }); + } + + reply.send({ status_code: 200, data: departmentNames }); + } catch (error) { + console.error("API Error:", error); + reply.status(500).send({ message: error.message }); + } +}; diff --git a/src/routes/departmentRoute.js b/src/routes/departmentRoute.js index 82ff9012..7a8a0c1a 100644 --- a/src/routes/departmentRoute.js +++ b/src/routes/departmentRoute.js @@ -597,5 +597,24 @@ module.exports = function (fastify, opts, next) { }, handler: departmentController.getCitiesByOfficeName, }); + + fastify.route({ + method: "GET", + url: "/api/departmentNameList/:city", + schema: { + tags: ["Department"], + description: "Get a list of department names for a given city", + summary: "Department names by city", + params: { + type: "object", + properties: { + city: { type: "string" } + }, + required: ["city"], + }, + }, + handler: departmentController.getDepartmentsByCity, + }); + next(); }; \ No newline at end of file