From 1ee73f44b6e1378abd918c5ef89a46505cbf38e1 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Wed, 29 Jan 2025 14:49:06 +0530 Subject: [PATCH] zone base locations --- src/controllers/departmentController.js | 54 ++++++++++++++++++++++++- src/routes/departmentRoute.js | 17 ++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/src/controllers/departmentController.js b/src/controllers/departmentController.js index a24b7235..b8e277c4 100644 --- a/src/controllers/departmentController.js +++ b/src/controllers/departmentController.js @@ -629,4 +629,56 @@ exports.addDepartment = async (request, reply) => { } catch (err) { reply.status(500).send({ message: err.message }); } - }; \ No newline at end of file + }; + + const getLocationsByZone = async (zone) => { + try { + const result = await City.aggregate([ + { + $match: { + zone: { $regex: `^${zone}$`, $options: "i" }, // Case-insensitive match for the zone + }, + }, + { + $unwind: "$location" // Unwind the location field if it is an array + }, + { + $group: { + _id: "$zone", // Group by zone + locations: { $addToSet: { $toUpper: "$location" } }, // Collect unique locations in uppercase + }, + }, + { + $project: { + _id: 0, // Exclude the _id field + zone: "$_id", // Include zone + locations: 1 // Just return the locations field as is + }, + }, + ]); + + return result; + } catch (err) { + console.error(err); + throw new Error("Error fetching locations."); + } + }; + + + + + exports.getLocationsByZone = async (req, reply) => { + try { + const { zone } = req.params; // Get zone from path params + + if (!zone) { + return reply.status(400).send({ message: "Zone is required." }); + } + + const locations = await getLocationsByZone(zone); + reply.send({ status_code: 200, data: locations }); + } catch (err) { + reply.status(500).send({ message: err.message }); + } + }; + \ No newline at end of file diff --git a/src/routes/departmentRoute.js b/src/routes/departmentRoute.js index 4d5d5934..cfeee179 100644 --- a/src/routes/departmentRoute.js +++ b/src/routes/departmentRoute.js @@ -381,6 +381,23 @@ module.exports = function (fastify, opts, next) { }, handler:departmentController.getZonebasedLocations }); + + fastify.route({ + method: "GET", + url: "/api/zonebasedlocations/:zone", + schema: { + tags: ["Department"], + description: "Get the locations by zone", + summary: "Get the locations by zone", + params: { + type: "object", + properties: { + zone: { type: "string" }, + }, + }, + }, + handler:departmentController.getLocationsByZone + }); next();