parks/scheduledata.js

  1. import Ajv from 'ajv';
  2. import {scheduleType} from './parkTypes.js';
  3. const ajv = new Ajv();
  4. const scheduleSchema = {
  5. type: 'array',
  6. items: {
  7. type: 'object',
  8. properties: {
  9. date: {
  10. type: 'string',
  11. // validate date format YYYY-MM-DD
  12. format: 'date',
  13. },
  14. type: {
  15. type: 'string',
  16. // limited to ENUM types scheduleType
  17. values: Object.values(scheduleType),
  18. },
  19. description: {
  20. type: 'string',
  21. },
  22. openingTime: {
  23. type: 'string',
  24. format: 'date-time',
  25. },
  26. closingTime: {
  27. type: 'string',
  28. format: 'date-time',
  29. },
  30. },
  31. required: ['date', 'type', 'openingTime', 'closingTime'],
  32. },
  33. };
  34. /**
  35. * Validate a schedula data object. Containing _id and a schedule array of schedules
  36. * @param {object} scheduleData
  37. * @return {array<string>} Array of errors, or null if successful
  38. */
  39. export function validateEntitySchedule(scheduleData) {
  40. const errors = [];
  41. if (!scheduleData._id) {
  42. errors.push('scheduleData missing _id field');
  43. }
  44. if (!scheduleData.schedule) {
  45. errors.push('scheduleData missing schedule field');
  46. }
  47. if (errors.length > 0) return errors;
  48. const validator = ajv.compile(scheduleSchema);
  49. if (!validator(scheduleData.schedule)) {
  50. return validator.errors;
  51. }
  52. return null;
  53. }