getImage.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict'
  2. import express from 'express'
  3. import path from 'path'
  4. import boom from 'boom'
  5. import { imagesPath, imageServedUrl } from '../../config'
  6. import { asyncMiddleware, checkSceneName, checkRequiredParameters, getSceneFilesData } from '../functions'
  7. const router = express.Router()
  8. /**
  9. * @typedef {Object} Image
  10. * @property {string} link the link (URL) to an image on the app
  11. * @property {string} path the path to the image in the file system
  12. * @property {string} fileName the name of the image
  13. * @property {string} sceneName the scene of the image
  14. * @property {number} quality the quality of the image
  15. * @property {string} ext the extension of the image
  16. */
  17. /**
  18. * Get the link and path to an image
  19. * @param {string} sceneName the scene to get the image from
  20. * @param {number} qualityInt the requested quality
  21. * @returns {Image} the link and path to the image
  22. */
  23. export const getImage = async (sceneName, qualityInt) => {
  24. const sceneData = await getSceneFilesData(sceneName)
  25. // Search an image with the requested quality in the scene
  26. for (const [imageName, imageData] of sceneData.entries())
  27. if (qualityInt === imageData.quality)
  28. return {
  29. link: `${imageServedUrl}/${sceneName}/${imageName}`,
  30. path: path.resolve(imagesPath, sceneName, imageName),
  31. fileName: imageName,
  32. sceneName,
  33. quality: imageData.quality,
  34. ext: imageData.ext
  35. }
  36. // Image not found
  37. throw boom.notFound(`The requested quality (${qualityInt}) was not found for the requested scene (${sceneName}).`)
  38. }
  39. router.get('/', asyncMiddleware(async (req, res) => {
  40. // Check the request contains all the required parameters
  41. checkRequiredParameters(['sceneName', 'imageQuality'], req.query)
  42. const { sceneName, imageQuality } = req.query
  43. let errorList = []
  44. // Check the scene name is valid
  45. try {
  46. checkSceneName(sceneName)
  47. }
  48. catch (err) {
  49. errorList.push(err.message)
  50. }
  51. // Check `imageQuality` is an integer
  52. const qualityInt = parseInt(imageQuality, 10)
  53. if (isNaN(qualityInt)) errorList.push('The specified quality is not an integer.')
  54. // Check there is no errors with parameters
  55. if (errorList.length > 0)
  56. throw boom.badRequest('Invalid query parameter(s).', errorList)
  57. const { link } = await getImage(sceneName, qualityInt)
  58. res.json({ link })
  59. }))
  60. export default router