import * as Multer from 'multer' ; import * as filenamify from 'filenamify' ; import { existsSync , mkdirSync } from 'fs' ; import { unsupportedMediaType } from '@hapi/boom' ; import { UPLOAD , SCALING } from '@config/environment.config' ; import { IUploadMulterOptions , IUploadOptions , IMedia , IStorage , IUpload } from '@interfaces' ; import { foldername , extension , getTypeOfMedia } from '@utils/string.util' ; import { FIELDNAME , IMAGE_MIME_TYPE } from '@enums' ; import { list } from '@utils/enum.util' ; class UploadConfiguration { private static instance : UploadConfiguration ; description options : IUploadOptions = { destination : UPLOAD . PATH , maxFiles : UPLOAD . MAX_FILES , filesize : UPLOAD . MAX_FILE_SIZE , wildcards : UPLOAD . WILDCARDS } ; description engine = Multer as ( options ? ) => IUpload ; private constructor ( ) { } description static get ( ) { if ( ! UploadConfiguration . instance ) { UploadConfiguration . instance = new UploadConfiguration ( ) ; } return UploadConfiguration . instance ; } description param destination param filesize param wildcards configuration ( options ? ) { return { storage : this . storage ( options . destination ) , limits : { fileSize : options . filesize } , fileFilter : ( req , file , next ) => { if ( options . wildcards . filter ( mime => file . mimetype === mime ) . length === 0 ) { return next ( unsupportedMediaType ( 'File mimetype not supported' ) , false ) ; } return next ( null , true ) ; } } ; } description param destination private storage ( destination ? ) { return Multer . diskStorage ( { destination : ( req , file , next ) => { let towards = `${ destination }/${ getTypeOfMedia ( file . mimetype ) }s` ; if ( IMAGE_MIME_TYPE [ file . mimetype ] ) { towards += `/${ SCALING . PATH_MASTER }` ; } towards += `/${ file . fieldname }` ; if ( list ( FIELDNAME ) . includes ( file . fieldname ) && ! existsSync ( towards ) ) { mkdirSync ( towards ) ; } next ( null , towards ) ; } , filename : ( req , file , next ) => { const name = filenamify ( foldername ( file . originalname ) , { replacement : '-' , maxLength : 123 } ) . replace ( ' ' , '-' ) . replace ( '_' , '-' ) . toLowerCase ( ) . concat ( '-' ) . concat ( Date . now ( ) . toString ( ) ) . concat ( '.' ) . concat ( extension ( file . originalname ) . toLowerCase ( ) ) ; next ( null , name ) ; } } ) as IStorage ; } } const configuration = UploadConfiguration . get ( ) ; export { configuration as UploadConfiguration } ;