|
| 1 | +"use strict"; |
| 2 | +/* |
| 3 | + * This file is part of the Image Squeezer. |
| 4 | + * |
| 5 | + * (c) Joshua Clifford Reyes <[email protected]> |
| 6 | + * |
| 7 | + * For the full copyright and license information, please view the LICENSE |
| 8 | + * file that was distributed with this source code. |
| 9 | + */ |
| 10 | +var __importDefault = (this && this.__importDefault) || function (mod) { |
| 11 | + return (mod && mod.__esModule) ? mod : { "default": mod }; |
| 12 | +}; |
| 13 | +Object.defineProperty(exports, "__esModule", { value: true }); |
| 14 | +const path_1 = __importDefault(require("path")); |
| 15 | +const file_type_1 = __importDefault(require("file-type")); |
| 16 | +const read_chunk_1 = __importDefault(require("read-chunk")); |
| 17 | +const FileFormatException_1 = require("../Exception/FileFormatException"); |
| 18 | +/** |
| 19 | + * File Format Resolver Class. |
| 20 | + * |
| 21 | + * The primary role of this class is to transform the details |
| 22 | + * of a given file path. It can be renaming of file name or changing the file extension, etc. |
| 23 | + * |
| 24 | + * @author Joshua Clifford Reyes <[email protected]> |
| 25 | + */ |
| 26 | +class FileFormatResolver { |
| 27 | + constructor(allowedExtensionMimeType) { |
| 28 | + this.allowedExtensionMimeType = {}; |
| 29 | + this.sourceFilePath = ''; |
| 30 | + this.fileNameExtension = ''; |
| 31 | + this.fileTypeDetails = { ext: '', mime: '' }; |
| 32 | + this.allowedExtensionMimeType = allowedExtensionMimeType; |
| 33 | + } |
| 34 | + setSourceFilePath(sourceFilePath) { |
| 35 | + this.sourceFilePath = sourceFilePath; |
| 36 | + } |
| 37 | + validate() { |
| 38 | + this.setFileNameExtension(); |
| 39 | + this.setFileTypeDetails(); |
| 40 | + if (typeof this.allowedExtensionMimeType[this.fileTypeDetails['ext']] === 'undefined') { |
| 41 | + throw FileFormatException_1.FileFormatException.extensionIsNotSupported(); |
| 42 | + } |
| 43 | + if (this.allowedExtensionMimeType[this.fileNameExtension] !== this.fileTypeDetails['mime']) { |
| 44 | + throw FileFormatException_1.FileFormatException.extensionAndMimeTypeIsNotEqual(); |
| 45 | + } |
| 46 | + } |
| 47 | + setFileNameExtension() { |
| 48 | + const FILE_NAME_EXT = 1; |
| 49 | + let filename = path_1.default.basename(this.sourceFilePath); |
| 50 | + let splittedFilename = filename.split('.'); |
| 51 | + this.fileNameExtension = splittedFilename[FILE_NAME_EXT]; |
| 52 | + } |
| 53 | + setFileTypeDetails() { |
| 54 | + const buffer = read_chunk_1.default.sync(this.sourceFilePath, 0, file_type_1.default.minimumBytes); |
| 55 | + let fileTypeDetails = file_type_1.default(buffer); |
| 56 | + if (typeof fileTypeDetails !== 'undefined' || fileTypeDetails) { |
| 57 | + this.fileTypeDetails['ext'] = fileTypeDetails.ext; |
| 58 | + this.fileTypeDetails['mime'] = fileTypeDetails.mime; |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | +exports.FileFormatResolver = FileFormatResolver; |
0 commit comments