UNPKG

sipp

Version:

An Opinionated, High-Productivity MVC Web Framework in TypeScript

73 lines 2.75 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PathDownload = exports.BufferDownload = exports.StreamDownload = exports.Download = void 0; const fs_1 = require("fs"); const path_1 = require("path"); const mime_types_1 = __importDefault(require("mime-types")); class Download { constructor(download, mimeType, fileName = 'download') { this.download = download; this.mimeType = mimeType; this.fileName = fileName; this.mimeType = mimeType || (fileName && mime_types_1.default.lookup(path_1.extname(fileName))) || 'text/plain'; } static from(download, mimeType, fileName) { switch (true) { case download instanceof Buffer: return new BufferDownload(download, mimeType, fileName); case typeof download === 'string': return new PathDownload(download, mimeType || mime_types_1.default.lookup(path_1.extname(download)), fileName); case download instanceof fs_1.ReadStream: return new StreamDownload(download, mimeType, fileName); case typeof download.toString === 'function': return new BufferDownload(Buffer.from(JSON.stringify(download)), 'application/json', fileName); default: throw new Error(`invalid download`); } } getFileName() { if (path_1.extname(this.fileName)) { return this.fileName; } return `${this.fileName}.${mime_types_1.default.extension(this.mimeType) || 'txt'}`; } } exports.Download = Download; class StreamDownload extends Download { handle(res) { this.download.pipe(res); } } exports.StreamDownload = StreamDownload; class BufferDownload extends Download { handle(res) { res.end(this.download); } } exports.BufferDownload = BufferDownload; class PathDownload extends Download { handle(res) { let fileName = this.fileName; if (!path_1.extname(this.fileName)) { fileName = `${this.fileName}${path_1.extname(this.download)}`; } res.download(this.download, fileName); } getFileName() { if (!this.fileName) { return path_1.basename(this.download); } if (path_1.extname(this.fileName)) { return this.fileName; } return `${this.fileName}${this.mimeType ? mime_types_1.default.extension(this.mimeType) : path_1.extname(this.download) || 'txt'}`; } } exports.PathDownload = PathDownload; //# sourceMappingURL=download.js.map