import { promises as fs , constants as fsConstants } from 'fs' ; import { goTry } from 'go-try' ; import sharp from 'sharp' ; const defaultJpgQuality = 70 ; const STORAGE_DIR = process . env . STORAGE_DIR ; const dirExists = async ( dirPath ) => { const { error } = await goTry ( ( ) => fs . access ( dirPath , fsConstants . F_OK ) ) ; return ! error ; } ; const createDir = async ( dirPath ) => { await fs . mkdir ( dirPath , { recursive : true } as any ) ; } ; export const createStorageIfNotExists = async ( ) => { const exists = await dirExists ( STORAGE_DIR ) ; if ( ! exists ) { await createDir ( STORAGE_DIR ) ; } } ; export interface ImageOptions { suffix ? : string ; width : number ; height ? : number ; } export const uploadFile = async ( file , fileId , options ? ) => { await createStorageIfNotExists ( ) ; const extension = '.jpg' ; let fileOut = `${ STORAGE_DIR }/${ fileId }${ extension }` ; const suffix = options ?. suffix ; if ( suffix ) { fileOut = fileOut . replace ( extension , `_${ suffix }${ extension }` ) ; } const info = await sharp ( file . buffer ) . jpeg ( { quality : defaultJpgQuality } ) . resize ( options ?. width , options ?. height ) . toFile ( fileOut ) ; return { ... info , url : `/${ fileOut }` } ; } ;