functions.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict'
  2. import _fs, { promises as fs } from 'fs'
  3. import boom from 'boom'
  4. import { apiConfig } from '../config'
  5. /**
  6. * Call the error handler if a middleware function throw an error
  7. *
  8. * @param {Function} fn original middleware function of the route
  9. * @returns {Function} the same middleware function of the route but error handled
  10. */
  11. export const asyncMiddleware = fn => (req, res, next) => {
  12. Promise.resolve(fn(req, res, next)).catch(err => {
  13. // Check whether the error is a boom error
  14. if (!err.isBoom) {
  15. // The error was not recognized, send a 500 HTTP error
  16. return next(boom.internal(err))
  17. }
  18. // It is a boom error, give it to express to handle it
  19. next(err)
  20. })
  21. }
  22. // Middleware to handle middleware errors
  23. export const errorHandler = (err, req, res, next) => {
  24. const { output: { payload } } = err
  25. console.error(`Error ${payload.statusCode} - ${payload.error}\n${payload.message}\n`)
  26. return res.status(payload.statusCode).json(payload)
  27. }
  28. /**
  29. * Get a list of all available scenes
  30. *
  31. * @returns {string[]} the available scenes
  32. */
  33. export const getAvailableScenes = async () => {
  34. try {
  35. // Check if the images directory exists
  36. await fs.access(apiConfig.imagesPath, _fs.constants.R_OK)
  37. }
  38. catch (err) {
  39. // The images directory does not exist or is not accessible
  40. throw boom.badRequest(`Can't access the "${apiConfig.imagesPath}" directory. Check it exists and you have read permission on it.`)
  41. }
  42. return fs.readdir(apiConfig.imagesPath)
  43. }