refactor the funtion keep comments add new if needed // Combined API for nearby,…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
refactor the funtion keep comments add new if needed
// Combined API for nearby, preference and filter based school search
const getSchoolsByMode = async (req, res) => {
const mode = req.query.mode || "filter"; // default to filter
if (mode === "nearby") {
// --- getNearBySchools logic ---
try {
const { rootUserId } = req;
if (!rootUserId) {
return res.status(401).json({
status: 401,
message: "Token is missing",
success: false,
});
}
const foundProfile = await studentProfile.findOne({ userId: rootUserId, isDeleted: false }).lean();
if (!foundProfile) {
return res.status(404).json({
status: 404,
message: "Student profile not found",
success: false,
});
}
const { schoolPreferences } = foundProfile;
const { location, radius: studentRadius } = schoolPreferences || {};
if (!location || !studentRadius) {
return res.status(400).json({
status: 400,
message: "Location and radius are required",
success: false,
});
}
const limit = parseInt(req.query.limit) || 10;
const page = parseInt(req.query.page) || 1;
const skip = (page - 1) * limit;
const search = req.query.search || "";
const sortField = req.query.sortField || "distanceInMeters";
const sortOrder = req.query.sortOrder === "desc" ? -1 : 1;
const searchQuery = search
? {
or: [
{ schoolName: { regex: search, options: "i" } },
{ religion: { regex: search, options: "i" } },
{ region: { regex: search, options: "i" } },
{ district: { regex: search, options: "i" } },
{ subCounty: { regex: search, options: "i" } },
{ description: { regex: search, options: "i" } },
{ affiliation: { regex: search, options: "i" } },
{ referral_code: { regex: search, options: "i" } },
{ schoolCategory: { regex: search, options: "i" } },
],
}
: {};
const combinedQuery = { isDeleted: false, ...searchQuery };
const maxSchoolRadius = await schoolProfile.findOne({ isDeleted: false }, { "targetArea.radius": 1 }).sort({ "targetArea.radius": -1 }).lean();
const maxPossibleDistance = studentRadius + (maxSchoolRadius?.targetArea?.radius || 100000);
const results = await schoolProfile.aggregate([
{
geoNear: {
near: location,
distanceField: "distanceInMeters",
maxDistance: maxPossibleDistance,
spherical: true,
query: combinedQuery,
},
},
{
addFields: {
combinedRadius: {
add: [studentRadius, { targetArea.radius", 100000] }],
},
studentRadius,
schoolRadius: { targetArea.radius", 100000] },
distanceInKm: {
round: [{ divide: ["distanceInMeters", 1000] }, 2],
},
},
},
{
match: {
expr: {
lte: ["combinedRadius"],
},
},
},
{
lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user",
// Ensure user is not deleted, isActive and is verified
pipeline: [
{
match: {
expr: {
and: [{ isDeleted", false] }, { isVerified", true] }, { isActive", true] }],
},
},
},
],
},
},
{ unwind: { path: "user", preserveNullAndEmptyArrays: true } },
{
project: {
"user.password": 0,
"user.otp": 0,
"user.otpExpiration": 0,
"user.otpGenerationTime": 0,
"user.otpUsed": 0,
"user.deviceTokens": 0,
"user.blockAllEmails": 0,
"user.isTwoFactorAuthentication": 0,
"user.deviceTokens": 0,
"user.isDeleted": 0,
"user.__v": 0,
isDeleted: 0,
__v: 0,
},
},
{
sort: {
[sortField]: sortOrder,
},
},
{
facet: {
paginatedResults: [{ skip: skip }, { limit: limit }],
totalCount: [{ count: "count" }],
},
},
]);
const paginatedResults = results[0].paginatedResults;
const totalCount = results[0].totalCount[0]?.count || 0;
return res.status(200).json({
status: 200,
message: "Nearby schools retrieved successfully",
success: true,
data: paginatedResults,
totalCount,
currentPage: page,
limit,
totalPages: Math.ceil(totalCount / limit),
});
} catch (error) {
console.error("Error in getSchools (nearby):", error);
return res.status(500).json({
status: 500,
message: "Internal server error",
success: false,
});
}
} else if (mode === "filter") {
// --- filter mode logic ---
try {
// Accept filters from req.body
let filters = req.body.filters;
if (!filters || typeof filters !== "object" || Array.isArray(filters)) {
return res.status(400).json({
status: 400,
message: "Filters object is required",
success: false,
});
}
// Pagination and sorting
const limit = parseInt(req.query.limit) || 10;
const page = parseInt(req.query.page) || 1;
const skip = (page - 1) * limit;
const sortField = req.query.sortField || "createdAt";
const sortOrder = req.query.sortOrder === "desc" ? -1 : 1;
// Build query, supporting dot notation for nested fields and elemMatch for arrays
function buildQuery(obj, prefix = "") {
let query = {};
for (const key in obj) {
const value = obj[key];
if (value !== undefined && value !== null && value !== "") {
if (Array.isArray(value) && value.length > 0 && typeof value[0] === "object" && !Array.isArray(value[0])) {
// Array of objects: use elemMatch
query[prefix ? ${prefix}.${key} : key] = { elemMatch: buildQuery(value[0]) };
} else if (typeof value === "object" && !Array.isArray(value)) {
// Nested object
Object.assign(query, buildQuery(value, prefix ? `{prefix}.{key}` : key));
} else {
// Primitive value
query[prefix ? `{prefix}.{key}` : key] = value;
}
}
}
return query;
}
const filterQuery = buildQuery(filters);
filterQuery.isDeleted = false;
const results = await schoolProfile.aggregate([
{ match: filterQuery },
{ sort: { [sortField]: sortOrder } },
{
lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user",
// Ensure user is not deleted, isActive and is verified
pipeline: [
{
match: {
expr: {
and: [{ eq: ["isDeleted", false] }, { eq: ["isVerified", true] }, { eq: ["isActive", true] }],
},
},
},
],
},
},
{ unwind: { path: "user", preserveNullAndEmptyArrays: true } },
{
project: {
"user.password": 0,
"user.otp": 0,
"user.otpExpiration": 0,
"user.otpGenerationTime": 0,
"user.otpUsed": 0,
"user.deviceTokens": 0,
"user.blockAllEmails": 0,
"user.isTwoFactorAuthentication": 0,
"user.deviceTokens": 0,
"user.isDeleted": 0,
"user.__v": 0,
isDeleted: 0,
__v: 0,
},
},
{
facet: {
paginatedResults: [{ skip: skip }, { limit: limit }],
totalCount: [{ count: "count" }],
},
},
]);
const paginatedResults = results[0].paginatedResults;
const totalCount = results[0].totalCount[0]?.count || 0;
return res.status(200).json({
status: 200,
message: "Schools retrieved successfully by filter",
success: true,
data: paginatedResults,
totalCount,
currentPage: page,
limit,
totalPages: Math.ceil(totalCount / limit),
});
} catch (error) {
console.error("Error in getSchools (filter):", error);
return res.status(500).json({
status: 500,
message: "Internal server error",
success: false,
});
}
} else if (mode === "preference") {
// --- getSchoolsByStudentPreference logic ---
try {
const { rootUserId } = req;
if (!rootUserId) {
return res.status(401).json({
status: 401,
message: "Token is missing",
success: false,
});
}
const foundProfile = await studentProfile.findOne({ userId: rootUserId }).lean();
if (!foundProfile) {
return res.status(404).json({
status: 404,
message: "Student profile not found",
success: false,
});
}
const { schoolPreferences } = foundProfile;
const { wholeNation, categories, regions, districts, subCounties } = schoolPreferences || {};
if (!wholeNation && !categories && !regions && !districts && !subCounties) {
return res.status(400).json({
status: 400,
message: "At least one preference or wholeNation must be provided",
success: false,
});
}
const limit = parseInt(req.query.limit) || 10;
const page = parseInt(req.query.page) || 1;
const skip = (page - 1) * limit;
const search = req.query.search || "";
const sortField = req.query.sortField || "createdAt";
const sortOrder = req.query.sortOrder === "desc" ? -1 : 1;
const preferenceQuery = {
isDeleted: false,
...(categories?.length && { schoolCategory: { in: categories.map((c) => c.toLowerCase()) } }),
...(regions && { "targetArea.regions": { in: regions.map((r) => r.toLowerCase()) } }),
...(districts?.length && { "targetArea.districts": { in: districts.map((d) => d.toLowerCase()) } }),
...(subCounties?.length && { "targetArea.subCounties": { in: subCounties.map((s) => s.toLowerCase()) } }),
};
const searchQuery = search
? {
or: [
{ schoolName: { regex: search, options: "i" } },
{ religion: { regex: search, options: "i" } },
{ region: { regex: search, options: "i" } },
{ district: { regex: search, options: "i" } },
{ subCounty: { regex: search, options: "i" } },
{ description: { regex: search, options: "i" } },
{ affiliation: { regex: search, options: "i" } },
{ referral_code: { regex: search, options: "i" } },
{ schoolCategory: { regex: search, options: "i" } },
],
}
: {};
const combinedQuery = search ? { and: [preferenceQuery, searchQuery] } : preferenceQuery;
if (wholeNation) {
const results = await schoolProfile.aggregate([
{ match: combinedQuery },
{ sort: { [sortField]: sortOrder } },
{
lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user",
// Ensure user is not deleted, isActive and is verified
pipeline: [
{
match: {
expr: {
and: [{ isDeleted", false] }, { isVerified", true] }, { isActive", true] }],
},
},
},
],
},
},
{ unwind: { path: "user", preserveNullAndEmptyArrays: true } },
{
project: {
"user.password": 0,
"user.otp": 0,
"user.otpExpiration": 0,
"user.otpGenerationTime": 0,
"user.otpUsed": 0,
"user.deviceTokens": 0,
"user.blockAllEmails": 0,
"user.isTwoFactorAuthentication": 0,
"user.deviceTokens": 0,
"user.isDeleted": 0,
"user.__v": 0,
isDeleted: 0,
__v: 0,
},
},
{
facet: {
paginatedResults: [{ skip: skip }, { limit: limit }],
totalCount: [{ count: "count" }],
},
},
]);
const paginatedResults = results[0].paginatedResults;
const totalCount = results[0].totalCount[0]?.count || 0;
return res.status(200).json({
status: 200,
message: "Nationwide schools retrieved successfully",
success: true,
data: paginatedResults,
totalCount,
currentPage: page,
limit,
totalPages: Math.ceil(totalCount / limit),
});
}
const results = await schoolProfile.aggregate([
{ match: combinedQuery },
{ sort: { [sortField]: sortOrder } },
{
lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user",
// Ensure user is not deleted, isActive and is verified
pipeline: [
{
match: {
expr: {
and: [{ eq: ["isDeleted", false] }, { eq: ["isVerified", true] }, { eq: ["isActive", true] }],
},
},
},
],
},
},
{
facet: {
paginatedResults: [{ skip: skip }, { limit: limit }],
totalCount: [{ $count: "count" }],
},
},
]);
const paginatedResults = results[0].paginatedResults;
const totalCount = results[0].totalCount[0]?.count || 0;
return res.status(200).json({
status: 200,
message: "Schools retrieved successfully",
success: true,
data: paginatedResults,
totalCount,
currentPage: page,
limit,
totalPages: Math.ceil(totalCount / limit),
});
} catch (error) {
console.error("Error in getSchools (preference):", error);
return res.status(500).json({
status: 500,
message: "Internal server error",
success: false,
});
}
} else {
return res.status(400).json({
status: 400,
message: "Invalid mode. Use 'nearby', 'filter', or 'preference'.",
success: false,
});
}
};
The provided function getSchoolsByMode can be refactored into separate functions for each mode (nearby, filter, preference) to improve readability and maintainability.
// Combined API for nearby, preference and filter based school search
const getSchoolsByMode = async (req, res) => {
const mode = req.query.mode || "filter"; // default to filter
switch (mode) {
case "nearby":
return getSchoolsNearby(req, res);
case "filter":
return getSchoolsByFilter(req, res);
case "preference":
return getSchoolsByPreference(req, res);
default:
return res.status(400).json({
status: 400,
message: "Invalid mode. Use 'nearby', 'filter', or 'preference'.",
success: false,
});
}
};
// --- getNearBySchools logic ---
const getSchoolsNearby = async (req, res) => {
try {
const { rootUserId } = req;
if (!rootUserId) {
return res.status(401).json({
status: 401,
message: "Token is missing",
success: false,
});
}
const foundProfile = await studentProfile.findOne({ userId: rootUserId, isDeleted: false }).lean();
if (!foundProfile) {
return res.status(404).json({
status: 404,
message: "Student profile not found",
success: false,
});
}
const { schoolPreferences } = foundProfile;
const { location, radius: studentRadius } = schoolPreferences || {};
if (!location || !studentRadius) {
return res.status(400).json({
status: 400,
message: "Location and radius are required",
success: false,
});
}
const limit = parseInt(req.query.limit) || 10;
const page = parseInt(req.query.page) || 1;
const skip = (page - 1) * limit;
const search = req.query.search || "";
const sortField = req.query.sortField || "distanceInMeters";
const sortOrder = req.query.sortOrder === "desc" ? -1 : 1;
const searchQuery = search
? {
$or: [
{ schoolName: { $regex: search, $options: "i" } },
{ religion: { $regex: search, $options: "i" } },
{ region: { $regex: search, $options: "i" } },
{ district: { $regex: search, $options: "i" } },
{ subCounty: { $regex: search, $options: "i" } },
{ description: { $regex: search, $options: "i" } },
{ affiliation: { $regex: search, $options: "i" } },
{ referral_code: { $regex: search, $options: "i" } },
{ schoolCategory: { $regex: search, $options: "i" } },
],
}
: {};
const combinedQuery = { isDeleted: false, ...searchQuery };
const maxSchoolRadius = await schoolProfile.findOne({ isDeleted: false }, { "targetArea.radius": 1 }).sort({ "targetArea.radius": -1 }).lean();
const maxPossibleDistance = studentRadius + (maxSchoolRadius?.targetArea?.radius || 100000);
const results = await schoolProfile.aggregate([
{
$geoNear: {
near: location,
distanceField: "distanceInMeters",
maxDistance: maxPossibleDistance,
spherical: true,
query: combinedQuery,
},
},
{
$addFields: {
combinedRadius: {
$add: [studentRadius, { $ifNull: ["$targetArea.radius", 100000] }],
},
studentRadius,
schoolRadius: { $ifNull: ["$targetArea.radius", 100000] },
distanceInKm: {
$round: [{ $divide: ["$distanceInMeters", 1000] }, 2],
},
},
},
{
$match: {
$expr: {
$lte: ["$distanceInMeters", "$combinedRadius"],
},
},
},
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user",
// Ensure user is not deleted, isActive and is verified
pipeline: [
{
$match: {
$expr: {
$and: [{ $eq: ["$isDeleted", false] }, { $eq: ["$isVerified", true] }, { $eq: ["$isActive", true] }],
},
},
},
],
},
},
{ $unwind: { path: "$user", preserveNullAndEmptyArrays: true } },
{
$project: {
"user.password": 0,
"user.otp": 0,
"user.otpExpiration": 0,
"user.otpGenerationTime": 0,
"user.otpUsed": 0,
"user.deviceTokens": 0,
"user.blockAllEmails": 0,
"user.isTwoFactorAuthentication": 0,
"user.deviceTokens": 0,
"user.isDeleted": 0,
"user.__v": 0,
isDeleted: 0,
__v: 0,
},
},
{
$sort: {
[sortField]: sortOrder,
},
},
{
$facet: {
paginatedResults: [{ $skip: skip }, { $limit: limit }],
totalCount: [{ $count: "count" }],
},
},
]);
const paginatedResults = results[0].paginatedResults;
const totalCount = results[0].totalCount[0]?.count || 0;
return res.status(200).json({
status: 200,
message: "Nearby schools retrieved successfully",
success: true,
data: paginatedResults,
totalCount,
currentPage: page,
limit,
totalPages: Math.ceil(totalCount / limit),
});
} catch (error) {
console.error("Error in getSchools (nearby):", error);
return res.status(500).json({
status: 500,
message: "Internal server error",
success: false,
});
}
};
// --- getSchoolsByFilter logic ---
const getSchoolsByFilter = async (req, res) => {
try {
// Accept filters from req.body
let filters = req.body.filters;
if (!filters || typeof filters !== "object" || Array.isArray(filters)) {
return res.status(400).json({
status: 400,
message: "Filters object is required",
success: false,
});
}
// Pagination and sorting
const limit = parseInt(req.query.limit) || 10;
const page = parseInt(req.query.page) || 1;
const skip = (page - 1) * limit;
const sortField = req.query.sortField || "createdAt";
const sortOrder = req.query.sortOrder === "desc" ? -1 : 1;
// Build query, supporting dot notation for nested fields and $elemMatch for arrays
function buildQuery(obj, prefix = "") {
let query = {};
for (const key in obj) {
const value = obj[key];
if (value !== undefined && value !== null && value !== "") {
if (Array.isArray(value) && value.length > 0 && typeof value[0] === "object" && !Array.isArray(value[0])) {
// Array of objects: use $elemMatch
query[prefix ? `${prefix}.${key}` : key] = { $elemMatch: buildQuery(value[0]) };
} else if (typeof value === "object" && !Array.isArray(value)) {
// Nested object
Object.assign(query, buildQuery(value, prefix ? `${prefix}.${key}` : key));
} else {
// Primitive value
query[prefix ? `${prefix}.${key}` : key] = value;
}
}
}
return query;
}
const filterQuery = buildQuery(filters);
filterQuery.isDeleted = false;
const results = await schoolProfile.aggregate([
{ $match: filterQuery },
{ $sort: { [sortField]: sortOrder } },
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user",
// Ensure user is not deleted, isActive and is verified
pipeline: [
{
$match: {
$expr: {
$and: [{ $eq: ["$isDeleted", false] }, { $eq: ["$isVerified", true] }, { $eq: ["$isActive", true] }],
},
},
},
],
},
},
{ $unwind: { path: "$user", preserveNullAndEmptyArrays: true } },
{
$project: {
"user.password": 0,
"user.otp": 0,
"user.otpExpiration": 0,
"user.otpGenerationTime": 0,
"user.otpUsed": 0,
"user.deviceTokens": 0,
"user.block