city based fetch state

master^2
Bhaskar 2 months ago
parent 0c7147392e
commit 061c02a162

@ -1743,6 +1743,26 @@ exports.getOffices = async (req, reply) => {
}
};
exports.getAllCities = async (req, reply) => {
try {
// Fetch only the majorCities field from all documents
const docs = await IndianLocations.find({}, "majorCities").lean();
// Flatten the array of arrays and remove duplicates
const cities = [...new Set(docs.flatMap(doc => doc.majorCities))];
// Sort alphabetically (case-insensitive)
cities.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
reply.send(cities);
} catch (err) {
console.error("Error fetching cities:", err);
reply.status(500).send({ error: "Failed to fetch cities" });
}
};
exports.getStaeBasedCites = async (request, reply) => {
try {
const { stateName } = request.params;
@ -1759,4 +1779,32 @@ exports.getOffices = async (req, reply) => {
};
exports.getCitiesBasedState = async (request, reply) => {
try {
// Match the param name from the route exactly
const { majorcities } = request.params;
if (!majorcities) {
return reply.status(400).send({ error: "majorcities param is required" });
}
// Case-insensitive regex match against elements in the array
const stateDoc = await IndianLocations.findOne(
{ majorCities: { $regex: new RegExp(`^${majorcities.trim()}$`, "i") } },
"state"
).lean();
if (!stateDoc) {
return reply.status(404).send({ error: "City not found" });
}
reply.send({ state: stateDoc.state });
} catch (err) {
console.error("Error fetching state:", err);
reply.status(500).send({ error: "Failed to fetch state" });
}
};

@ -728,11 +728,22 @@ module.exports = function (fastify, opts, next) {
handler:departmentController.getAllStates
});
fastify.route({
method: "GET",
url: "/api/Cities",
schema: {
tags: ["Admin"],
description: "Get the Cities",
summary: "Get the Cities",
},
handler:departmentController.getAllCities
});
fastify.route({
method: "GET",
url: "/api/states/cities/:stateName",
schema: {
tags: ["Department"],
tags: ["Admin"],
description: "Get the States by cities",
summary: "Get the states by cites",
params: {
@ -745,5 +756,23 @@ module.exports = function (fastify, opts, next) {
},
handler:departmentController.getStaeBasedCites
});
fastify.route({
method: "GET",
url: "/api/cities/states/:majorcities",
schema: {
tags: ["Admin"],
description: "Get the Cities by state",
summary: "Get the cities by state",
params: {
type: "object",
properties: {
majorcities: { type: "string" },
},
},
},
handler:departmentController.getCitiesBasedState
});
next();
};
Loading…
Cancel
Save