From d6f28003b3a42b856bd882fa68040a263def65a2 Mon Sep 17 00:00:00 2001 From: miguel Date: Tue, 12 Aug 2025 14:56:34 -0600 Subject: [PATCH] Implement deleteAllCarrusel method to remove all images and database records from the carrusel --- src/carrusel/carrusel.controller.ts | 5 +++ src/carrusel/carrusel.service.ts | 50 +++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 2 deletions(-) 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, + }); + } + } }