/**
* Validates data for API endpoints related to maintenance tasks.
* Uses hardcoded limits for validation.
*/
const validateMaintenanceData = (data) => {
// Hardcoded limits (example values)
const MAX_TASK_COUNT = 10;
const MAX_TASK_DURATION = 720; // minutes (12 hours)
const MAX_PRIORITY = 3;
const MIN_TASK_DURATION = 60; //minutes
if (!data) {
return { error: "Data is required." };
}
if (typeof data !== 'object' || Array.isArray(data)) {
return { error: "Data must be an object or an array of objects." };
}
if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
const task = data[i];
if (typeof task !== 'object' || task === null) {
return { error: `Invalid task at index ${i}. Task must be an object.` };
}
if (typeof task.task_count !== 'number' || task.task_count < 0 || task.task_count > MAX_TASK_COUNT) {
return { error: `Invalid task_count at index ${i}. Must be a number between 0 and ${MAX_TASK_COUNT}.` };
}
if (typeof task.duration !== 'number' || task.duration < MIN_TASK_DURATION || task.duration > MAX_TASK_DURATION) {
return { error: `Invalid duration at index ${i}. Must be between ${MIN_TASK_DURATION} and ${MAX_TASK_DURATION} minutes.` };
}
if (typeof task.priority !== 'number' || task.priority < 1 || task.priority > MAX_PRIORITY) {
return { error: `Invalid priority at index ${i}. Must be between 1 and ${MAX_PRIORITY}.` };
}
}
} else {
//Validate single task object
if (typeof data.task_count !== 'number' || data.task_count < 0 || data.task_count > MAX_TASK_COUNT) {
return { error: `Invalid task_count. Must be a number between 0 and ${MAX_TASK_COUNT}.` };
}
if (typeof data.duration !== 'number' || data.duration < MIN_TASK_DURATION || data.duration > MAX_TASK_DURATION) {
return { error: `Invalid duration. Must be between ${MIN_TASK_DURATION} and ${MAX_TASK_DURATION} minutes.` };
}
if (typeof data.priority !== 'number' || data.priority < 1 || data.priority > MAX_PRIORITY) {
return { error: `Invalid priority. Must be between 1 and ${MAX_PRIORITY}.` };
}
}
return { success: true }; // Data is valid
};
// Example Usage (for testing)
// const validData = [{ task_count: 5, duration: 360, priority: 2 }];
// const invalidData = [{ task_count: 12, duration: 86400, priority: 5 }]; //duration too long, task_count too high
// const invalidData2 = "not an object";
// const invalidData3 = [{task_count: "abc", duration: 100, priority:1}];
// console.log(validateMaintenanceData(validData));
// console.log(validateMaintenanceData(invalidData));
// console.log(validateMaintenanceData(invalidData2));
// console.log(validateMaintenanceData(invalidData3));
Add your comment