import { getFile } from '../files.js' import { NotFoundError } from '../errors.js' import createError from 'http-errors' export default async function serveFilePlugin (fastify, options) { fastify.get('*', async (req, reply) => { try { const version = reply.version const url = req.urlData('path').substr(process.env.APP_ROOT.length - 1) const path = url === '/' ? '/index.html' : url const { body, headers } = await getFile({ version, path }) Object.entries(headers).forEach(([key, value]) => { reply.header(key, value) }) reply.send(body) } catch (err) { const errors = err.errors || [err] const fileNotFound = errors.reduce((memo, error) => memo && error instanceof NotFoundError, true) if (fileNotFound) throw createError(404, `File "${req.urlData('path')}" does not exist.`) throw err } }) }