UNPKG

@opengis/fastify-table

Version:

core-plugins

73 lines (58 loc) 2.3 kB
import path from 'node:path'; import mime from '../../../plugins/file/providers/mime/index.js'; import isFileExists from '../../../plugins/file/isFileExists.js'; import downloadFile from '../../../plugins/file/downloadFile.js'; import { applyHook } from '../../../../utils.js'; /** * Апі використовується для отримання різних файлів і можливістю змінювати їх * * @method GET * @summary Отримання файлів з директорії системи * @priority 5 * @alias files * @type api * @tag file * @requires getFile * @requires mime * @param {Object} params Параметри URL * @errors 500 * @returns {Number} status Номер помилки * @returns {String} error Опис помилки * @returns {Object} headers Заголовки HTTP * @returns {String} pipe Шлях до файла для скачування або відображення */ export default async function getFile({ params = {}, }, reply) { if (!params?.['*']) { return { message: 'not enough params', status: 400 }; } if (params['*']?.includes('../')) { return { message: 'wrong params', status: 403 }; } const relpath = (params['*'].startsWith('/') ? params['*'].slice(1) : params['*']).replace(/files\//g, '') + (params['*'].endsWith('/') ? 'index.html' : ''); if (!relpath) { return { message: 'No required param \'filename\'', status: 400 }; } if (relpath.includes('..')) { return { message: 'wrong params', status: 400 }; } const hookData = await applyHook('preFile', { relpath, reply }); if (hookData) return hookData; const filepath = path.join('files', relpath); const exists = await isFileExists(filepath); if (!exists) { return { message: 'file not found', status: 404 }; } const fileStream = await downloadFile(filepath); if (!fileStream) { return { message: 'file not found', status: 404 }; } const headers = { 'Content-Disposition': `inline; filename=${path.basename(filepath)}`, 'Cache-Control': 'max-age=86400', 'Content-Type': `${mime(filepath)}`, // ; charset=utf-8 --- untested }; reply.headers(headers); return fileStream; }