import { BadRequestException, Controller, Delete, Get, HttpException, HttpStatus, Param, Post, Res, UploadedFile, UseInterceptors, } from '@nestjs/common'; import { FileInterceptor } from '@nestjs/platform-express'; import { Response } from 'express'; import * as fs from 'fs'; import { diskStorage } from 'multer'; import * as path from 'path'; @Controller('carousel') export class CarouselController { private images: string[] = []; @Post('/imagenes') @UseInterceptors( FileInterceptor('file', { storage: diskStorage({ destination: './public', filename: function (req, file, cb) { const directory = './public'; const filePath = `${directory}/${file.originalname}`; if (fs.existsSync(filePath)) { cb( new BadRequestException( `Ya existe un archivo con el nombre: '${file.originalname}'. Si está seguro de que no es el mismo, cambie el nombre del archivo.`, ), null, ); } else { cb(null, file.originalname); } }, }), fileFilter: function (req, file, cb) { const filetypes = /jpeg|jpg|webp|png/; const extname = filetypes.test( path.extname(file.originalname).toLowerCase(), ); const mimetype = filetypes.test(file.mimetype); if (mimetype && extname) { return cb(null, true); } cb( new BadRequestException( 'Lo sentimos, para mejorar la calidad de las imagenes en el carousel solo se aceptan imagenes con terminación: .jpeg .jpg .png .webp', ), false, ); }, }), ) async addImage(@UploadedFile() file) { return { msg: 'Imagen guardada con exito :)' }; } @Delete('/imagenes/:nombreArchivo') async deleteImage(@Param('nombreArchivo') nombreArchivo: string) { try { await fs.promises.unlink(`./public/${nombreArchivo}`); return { message: 'Imagen eliminada exitosamente' }; } catch (err) { throw new Error('Error al eliminar la imagen'); } } @Get('/imagenes') async getImages(@Res() res: Response) { // Leer el directorio 'public' para obtener el nombre de todos los archivos const fileNames = await fs.promises.readdir('./public'); // Generar la URL para cada archivo y agregarla a un arreglo // Filtrar solo las imágenes con las terminaciones "jpg", "webp" y "png" const imageNames = fileNames.filter((fileName) => ['.jpg', '.webp', '.png'].includes(path.extname(fileName)), ); const imageUrls = imageNames.map((imageName) => `public/${imageName}`); // Devolver el arreglo de URLs como respuesta return res.json(imageUrls); } }