Implement deleteAllCarrusel method to remove all images and database records from the carrusel

This commit is contained in:
miguel
2025-08-12 14:56:34 -06:00
parent 5c68472a85
commit d6f28003b3
2 changed files with 53 additions and 2 deletions
+5
View File
@@ -57,4 +57,9 @@ export class CarruselController {
getAllImagenes() {
return this.carruselService.getAllImages();
}
@Delete('deleteAll')
deleteAllCarrusel() {
return this.carruselService.deleteAllCarrusel();
}
}
+48 -2
View File
@@ -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<Carrusel[]> {
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,
});
}
}
}