feat: endpoint /v1/activity/list?isStudentLed={true/false}

This commit is contained in:
JamesFlare1212
2025-05-14 00:30:43 -04:00
parent 2db16d5e80
commit d81078c62d

138
index.ts
View File

@@ -114,9 +114,10 @@ async function fetchProcessAndStoreActivity(activityId: string): Promise<Process
app.get('/', (_req: Request, res: Response) => { app.get('/', (_req: Request, res: Response) => {
res.send('Welcome to the DSAS CCA API!<br/>\ res.send('Welcome to the DSAS CCA API!<br/>\
GET /v1/activity/list<br/>\ GET /v1/activity/list<br/>\
GET /v1/activity/list?category=<br/>\ GET /v1/activity/list?category={category name}<br/>\
GET /v1/activity/list?academicYear=<br/>\ GET /v1/activity/list?academicYear={YYYY/YYYY}<br/>\
GET /v1/activity/list?grade=<br/>\ GET /v1/activity/list?grade={1-12}<br/>\
GET /v1/activity/list?isStudentLed={true/false}<br/>\
GET /v1/activity/category<br/>\ GET /v1/activity/category<br/>\
GET /v1/activity/academicYear<br/>\ GET /v1/activity/academicYear<br/>\
GET /v1/activity/:activityId<br/>\ GET /v1/activity/:activityId<br/>\
@@ -129,113 +130,100 @@ app.get('/v1/activity/list', async (req: Request, res: Response) => {
const category = req.query.category as string | undefined; const category = req.query.category as string | undefined;
const academicYear = req.query.academicYear as string | undefined; const academicYear = req.query.academicYear as string | undefined;
const grade = req.query.grade as string | undefined; const grade = req.query.grade as string | undefined;
// Validate academicYear format if provided (YYYY/YYYY) const isStudentLedQ = req.query.isStudentLed as string | undefined;
/* ---------- validate query params ---------- */
// academicYear (YYYY/YYYY)
if (academicYear !== undefined) { if (academicYear !== undefined) {
const academicYearRegex = /^\d{4}\/\d{4}$/; const academicYearRegex = /^\d{4}\/\d{4}$/;
if (!academicYearRegex.test(academicYear)) { if (!academicYearRegex.test(academicYear)) {
return res.status(400).json({ error: 'Invalid academicYear format. Expected format: YYYY/YYYY' }); return res.status(400).json({ error: 'Invalid academicYear format. Expected format: YYYY/YYYY' });
} }
} }
// Validate grade if provided // grade (112)
let validGrade: number | null = null; let validGrade: number | null = null;
if (grade !== undefined) { if (grade !== undefined) {
const parsedGrade = parseInt(grade, 10); const parsedGrade = parseInt(grade, 10);
if (!isNaN(parsedGrade) && parsedGrade > 0 && parsedGrade <= 12) { if (isNaN(parsedGrade) || parsedGrade < 1 || parsedGrade > 12) {
validGrade = parsedGrade;
} else {
return res.status(400).json({ error: 'Invalid grade parameter. Must be a number between 1 and 12.' }); return res.status(400).json({ error: 'Invalid grade parameter. Must be a number between 1 and 12.' });
} }
validGrade = parsedGrade;
} }
// isStudentLed ("true" | "false")
let isStudentLedFilter: boolean | null = null;
if (isStudentLedQ !== undefined) {
if (isStudentLedQ === 'true') isStudentLedFilter = true;
else if (isStudentLedQ === 'false') isStudentLedFilter = false;
else {
return res.status(400).json({ error: 'Invalid isStudentLed parameter. Must be "true" or "false".' });
}
}
logger.info(`Request /v1/activity/list filters: ${JSON.stringify({ category, academicYear, grade: validGrade, isStudentLed: isStudentLedFilter })}`);
logger.info(`Request received for /v1/activity/list with filters: ${JSON.stringify({category, academicYear, grade: validGrade})}`); /* ---------- fetch & cache ---------- */
const activityKeys = await getAllActivityKeys(); const activityKeys = await getAllActivityKeys();
const clubList: Record<string, {name: string, photo: string}> = {}; const clubList: Record<string, { name: string; photo: string }> = {};
if (!activityKeys || activityKeys.length === 0) { if (!activityKeys || activityKeys.length === 0) {
logger.info('No activity keys found in Redis for list.'); logger.info('No activity keys found in Redis for list.');
return res.json({}); return res.json({});
} }
// Fetch all activity data in parallel
const allActivityDataPromises = activityKeys.map(async (key) => {
const activityId = key.substring(ACTIVITY_KEY_PREFIX.length);
return getActivityData(activityId);
});
const allActivities = await Promise.all(allActivityDataPromises); const allActivities = await Promise.all(
// First pass: collect all available categories for validation activityKeys.map(async k => getActivityData(k.substring(ACTIVITY_KEY_PREFIX.length)))
);
/* ---------- gather available filter values for validation ---------- */
const availableCategories = new Set<string>(); const availableCategories = new Set<string>();
const availableAcademicYears = new Set<string>(); const availableAcademicYears = new Set<string>();
allActivities.forEach((activityData: ActivityData | null) => { allActivities.forEach(a => {
if (activityData && if (a && !a.error && a.source !== 'api-fetch-empty') {
!activityData.error && if (a.category) availableCategories.add(a.category);
activityData.source !== 'api-fetch-empty') { if (a.academicYear) availableAcademicYears.add(a.academicYear);
if (activityData.category) {
availableCategories.add(activityData.category);
}
if (activityData.academicYear) {
availableAcademicYears.add(activityData.academicYear);
}
} }
}); });
// Validate category against available categories
if (category && !availableCategories.has(category)) { if (category && !availableCategories.has(category)) {
return res.status(400).json({ return res.status(400).json({ error: 'Invalid category parameter. Category not found.', availableCategories: [...availableCategories] });
error: 'Invalid category parameter. Category not found.',
availableCategories: Array.from(availableCategories)
});
} }
// Validate academicYear against available years
if (academicYear && !availableAcademicYears.has(academicYear)) { if (academicYear && !availableAcademicYears.has(academicYear)) {
return res.status(400).json({ return res.status(400).json({ error: 'Invalid academicYear parameter. Academic year not found.', availableAcademicYears: [...availableAcademicYears] });
error: 'Invalid academicYear parameter. Academic year not found.',
availableAcademicYears: Array.from(availableAcademicYears)
});
} }
// Apply filters and collect club data
allActivities.forEach((activityData: ActivityData | null) => { /* ---------- apply filters ---------- */
if (activityData && allActivities.forEach(a => {
activityData.id && if (
activityData.name && a &&
!activityData.error && a.id &&
activityData.source !== 'api-fetch-empty') { a.name &&
// Check if it matches category filter if provided !a.error &&
if (category && activityData.category !== category) { a.source !== 'api-fetch-empty'
return; // Skip this activity ) {
} // category
// Check if it matches academicYear filter if provided if (category && a.category !== category) return;
if (academicYear && activityData.academicYear !== academicYear) { // academicYear
return; // Skip this activity if (academicYear && a.academicYear !== academicYear) return;
} // grade
// Check if it matches grade filter if provided
if (validGrade !== null) { if (validGrade !== null) {
// Skip if grades are null if (!a.grades || a.grades.min == null || a.grades.max == null) return;
if (!activityData.grades || const minG = parseInt(a.grades.min, 10);
activityData.grades.min === null || const maxG = parseInt(a.grades.max, 10);
activityData.grades.max === null) { if (isNaN(minG) || isNaN(maxG) || validGrade < minG || validGrade > maxG) return;
return; // Skip this activity
} }
// isStudentLed
const minGrade = parseInt(activityData.grades.min, 10); if (isStudentLedFilter !== null) {
const maxGrade = parseInt(activityData.grades.max, 10); // Treat missing value as false
// Skip if grade is out of range or if parsing fails const led = a.isStudentLed ?? false;
if (isNaN(minGrade) || isNaN(maxGrade) || validGrade < minGrade || validGrade > maxGrade) { if (led !== isStudentLedFilter) return;
return; // Skip this activity
} }
} clubList[a.id] = { name: a.name, photo: a.photo || '' };
// Add to result object with name and photo
clubList[activityData.id] = {
name: activityData.name,
photo: activityData.photo || ""
};
} }
}); });
logger.info(`Returning list of ${Object.keys(clubList).length} valid clubs after filtering.`); logger.info(`Returning ${Object.keys(clubList).length} clubs after filtering.`);
res.json(clubList); res.json(clubList);
} catch (err) {
} catch (error) { logger.error('Error in /v1/activity/list endpoint:', err);
logger.error('Error in /v1/activity/list endpoint:', error);
res.status(500).json({ error: 'An internal server error occurred while generating activity list.' }); res.status(500).json({ error: 'An internal server error occurred while generating activity list.' });
} }
}); });