From 19401176945948f17f5283490c41d8316b60e283 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Thu, 30 Jan 2025 12:50:20 +0530 Subject: [PATCH] get all department names --- src/controllers/departmentController.js | 45 +++++++++++++++++++++++++ src/routes/departmentRoute.js | 18 ++++++++++ 2 files changed, 63 insertions(+) diff --git a/src/controllers/departmentController.js b/src/controllers/departmentController.js index 12e5489d..939462d6 100644 --- a/src/controllers/departmentController.js +++ b/src/controllers/departmentController.js @@ -765,4 +765,49 @@ exports.addDepartment = async (request, reply) => { reply.status(500).send({ message: err.message }); } }; + + + const getDepartmentNames = async () => { + try { + const result = await Deparments.aggregate([ + { + $group: { + _id: { + $toUpper: { $trim: { input: "$departmentName" } }, // Convert to uppercase & trim spaces + }, + }, + }, + { + $sort: { _id: 1 } // Sort alphabetically + }, + { + $group: { + _id: null, + departmentNames: { $addToSet: "$_id" } // Collect unique values in an array + } + }, + { + $project: { + _id: 0, + departmentNames: 1 // Return only the array + }, + } + ]); + + return result.length > 0 ? result[0].departmentNames : []; // Return an empty array if no data + } catch (err) { + console.error(err); + throw new Error("Error fetching department names."); + } + }; + + // API Route + exports.getAllDepartmentNames = async (req, reply) => { + try { + const departments = await getDepartmentNames(); + reply.send({ status_code: 200, data: departments }); + } 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 f2cfc739..67f6dc14 100644 --- a/src/routes/departmentRoute.js +++ b/src/routes/departmentRoute.js @@ -432,5 +432,23 @@ module.exports = function (fastify, opts, next) { }, handler:departmentController.getDepartments }); + + + fastify.get("/api/getalldepartmentNames", { + schema: { + tags: ["Department"], + description: "This is for Get all departmentNames Data", + summary: "This is for to Get all departmentNames Data", + + security: [ + { + basicAuth: [], + }, + ], + }, + //preHandler: fastify.auth([fastify.authenticate]), + handler: departmentController.getAllDepartmentNames, + }); + next(); }; \ No newline at end of file