diff --git a/src/carrusel/carrusel.controller.ts b/src/carrusel/carrusel.controller.ts index 8ad3d09..d7102ca 100644 --- a/src/carrusel/carrusel.controller.ts +++ b/src/carrusel/carrusel.controller.ts @@ -57,4 +57,9 @@ export class CarruselController { getAllImagenes() { return this.carruselService.getAllImages(); } + + @Delete('deleteAll') + deleteAllCarrusel() { + return this.carruselService.deleteAllCarrusel(); + } } diff --git a/src/carrusel/carrusel.service.ts b/src/carrusel/carrusel.service.ts index 4a6c602..7c4624b 100644 --- a/src/carrusel/carrusel.service.ts +++ b/src/carrusel/carrusel.service.ts @@ -1,10 +1,14 @@ -import { BadRequestException, Injectable, InternalServerErrorException } from '@nestjs/common'; +import { + BadRequestException, + Injectable, + InternalServerErrorException, +} from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Carrusel } from 'src/entities/carrusel.entity'; import { Repository } from 'typeorm'; import { carruselDto } from './dto/carruselDto.dto'; import * as fs from 'fs'; -import { Response } from 'express'; +import * as path from 'path'; @Injectable() export class CarruselService { @@ -74,4 +78,46 @@ export class CarruselService { getAllImages(): Promise { return this.carruselRepository.find(); } + + async deleteAllCarrusel(): Promise<{ message: string }> { + try { + // Obtener todas las imágenes del carrusel + const images = await this.carruselRepository.find(); + + // Eliminar archivos físicos de la carpeta public/carrusel + const carruselDir = './public/carrusel'; + + if (fs.existsSync(carruselDir)) { + // Leer todos los archivos en el directorio + const files = await fs.promises.readdir(carruselDir); + + // Eliminar cada archivo + for (const file of files) { + const filePath = path.join(carruselDir, file); + try { + await fs.promises.unlink(filePath); + console.log(`✅ Archivo eliminado: ${filePath}`); + } catch (fileError) { + console.warn( + `⚠️ No se pudo eliminar el archivo: ${filePath}`, + fileError.message, + ); + } + } + } + + // Eliminar todos los registros de la base de datos + await this.carruselRepository.delete({}); + + return { + message: `Carrusel limpiado exitosamente. Se eliminaron ${images.length} imágenes y registros.`, + }; + } catch (error) { + console.error('❌ Error al limpiar el carrusel:', error); + throw new InternalServerErrorException({ + message: 'Ocurrió un error inesperado al limpiar el carrusel', + error: error.message, + }); + } + } }