import { BaseService } from "@triptyk/nfw-core" ; import { Request } from "express" ; import { sync as mkdirpSync } from "mkdirp" ; import * as Multer from "multer" ; import { autoInjectable , singleton } from "tsyringe" ; enum StorageType { MEMORY , DISK } @ singleton ( ) @ autoInjectable ( ) class MulterService extends BaseService { private multers = { [ StorageType . MEMORY ] : { } , [ StorageType . DISK ] : { } } ; public init ( ) { return true ; } public makeMulter ( type , destinationOrName , validate , maxFileSize ) { if ( this . multers [ type ] [ destinationOrName ] ) { return this . multers [ type ] [ destinationOrName ] ; } if ( type === StorageType . DISK ) { mkdirpSync ( destinationOrName ) ; } const storage = type === StorageType . DISK ? Multer . diskStorage ( { destination ( req , file , next ) { next ( null , destinationOrName ) ; } , filename ( req , file , next ) { next ( null , `${ file . originalname }-${ Date . now ( ) }` ) ; } } ) : Multer . memoryStorage ( ) ; const built = Multer ( { fileFilter : validate , limits : { fileSize : maxFileSize } , storage } ) ; return ( this . multers [ type ] [ destinationOrName ] = built ) ; } } export { StorageType , MulterService } ;