Source: functions/loadAdvents.js

  1. /**
  2. * @module loadAdvents
  3. */
  4. const fs = require('fs');
  5. const validateSchema = require('../schema/validateSchema');
  6. /**
  7. * @function
  8. * @name loadAdvents
  9. * @description Load and Validate Advents from Directory
  10. * @param {string} dirPath Path to Advents Directory
  11. * @returns {Object[]} Array of Valid Advents
  12. * @throws An Error if Invalid Advents exist, printing the File Names
  13. */
  14. function loadAdvents(dirPath) {
  15. // Process JSON Files
  16. const { valid, invalid, tags } = fs.readdirSync(dirPath)
  17. // Filter *.advent.js(on)? Files
  18. .filter(name => (
  19. fs.lstatSync(`${dirPath}/${name}`).isFile() &&
  20. (name.endsWith('.advent.js') || name.endsWith('.advent.json'))
  21. ))
  22. // Load Advents
  23. .map(name => ({
  24. name,
  25. data: require(`${dirPath}/${name}`)
  26. }))
  27. // Group Valid and Invalid Advents
  28. .reduce((advents, { name, data }) => {
  29. const validatedData = validateSchema(data);
  30. if (validatedData !== false) {
  31. advents.valid.push(validatedData);
  32. for (const tag of validatedData.tags) {
  33. if (!advents.tags.has(tag)) {
  34. advents.tags.set(tag, true);
  35. }
  36. }
  37. } else {
  38. advents.invalid.push(name);
  39. }
  40. return advents;
  41. }, { valid: [], invalid: [], tags: new Map() });
  42. // Log Invalid Advents
  43. if (invalid.length !== 0) {
  44. throw new Error(
  45. `Invalid Advents in "${dirPath}"\n` +
  46. invalid.map(name => `[ERROR]: - ${dirPath}/${name}`).join('\n')
  47. );
  48. }
  49. // Return Valid Advents
  50. return { advents: valid, tags };
  51. }
  52. module.exports = loadAdvents;