1. /**
  2. * Validates data for API endpoints related to maintenance tasks.
  3. * Uses hardcoded limits for validation.
  4. */
  5. const validateMaintenanceData = (data) => {
  6. // Hardcoded limits (example values)
  7. const MAX_TASK_COUNT = 10;
  8. const MAX_TASK_DURATION = 720; // minutes (12 hours)
  9. const MAX_PRIORITY = 3;
  10. const MIN_TASK_DURATION = 60; //minutes
  11. if (!data) {
  12. return { error: "Data is required." };
  13. }
  14. if (typeof data !== 'object' || Array.isArray(data)) {
  15. return { error: "Data must be an object or an array of objects." };
  16. }
  17. if (Array.isArray(data)) {
  18. for (let i = 0; i < data.length; i++) {
  19. const task = data[i];
  20. if (typeof task !== 'object' || task === null) {
  21. return { error: `Invalid task at index ${i}. Task must be an object.` };
  22. }
  23. if (typeof task.task_count !== 'number' || task.task_count < 0 || task.task_count > MAX_TASK_COUNT) {
  24. return { error: `Invalid task_count at index ${i}. Must be a number between 0 and ${MAX_TASK_COUNT}.` };
  25. }
  26. if (typeof task.duration !== 'number' || task.duration < MIN_TASK_DURATION || task.duration > MAX_TASK_DURATION) {
  27. return { error: `Invalid duration at index ${i}. Must be between ${MIN_TASK_DURATION} and ${MAX_TASK_DURATION} minutes.` };
  28. }
  29. if (typeof task.priority !== 'number' || task.priority < 1 || task.priority > MAX_PRIORITY) {
  30. return { error: `Invalid priority at index ${i}. Must be between 1 and ${MAX_PRIORITY}.` };
  31. }
  32. }
  33. } else {
  34. //Validate single task object
  35. if (typeof data.task_count !== 'number' || data.task_count < 0 || data.task_count > MAX_TASK_COUNT) {
  36. return { error: `Invalid task_count. Must be a number between 0 and ${MAX_TASK_COUNT}.` };
  37. }
  38. if (typeof data.duration !== 'number' || data.duration < MIN_TASK_DURATION || data.duration > MAX_TASK_DURATION) {
  39. return { error: `Invalid duration. Must be between ${MIN_TASK_DURATION} and ${MAX_TASK_DURATION} minutes.` };
  40. }
  41. if (typeof data.priority !== 'number' || data.priority < 1 || data.priority > MAX_PRIORITY) {
  42. return { error: `Invalid priority. Must be between 1 and ${MAX_PRIORITY}.` };
  43. }
  44. }
  45. return { success: true }; // Data is valid
  46. };
  47. // Example Usage (for testing)
  48. // const validData = [{ task_count: 5, duration: 360, priority: 2 }];
  49. // const invalidData = [{ task_count: 12, duration: 86400, priority: 5 }]; //duration too long, task_count too high
  50. // const invalidData2 = "not an object";
  51. // const invalidData3 = [{task_count: "abc", duration: 100, priority:1}];
  52. // console.log(validateMaintenanceData(validData));
  53. // console.log(validateMaintenanceData(invalidData));
  54. // console.log(validateMaintenanceData(invalidData2));
  55. // console.log(validateMaintenanceData(invalidData3));

Add your comment