diff --git a/docs/api-reference.md b/docs/api-reference.md index b2fb9ac..592962d 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -117,6 +117,42 @@ Recupera la información detallada de un héroe específico usando su ID. } ``` +### Eliminar un héroe por ID + +Elimina un héroe específico usando su ID. + +**Endpoint**: `DELETE /api/heroes/:id` + +**Parámetros de ruta**: + +| Parámetro | Tipo | Descripción | Ejemplo | +|-----------|--------|------------------|-----------| +| id | number | ID del héroe | /api/heroes/1 | + +**Respuesta exitosa** (código 200): + +```json +{ + "message": "Hero deleted successfully" +} +``` + +**Respuesta de error** (código 404): + +```json +{ + "error": "Hero not found" +} +``` + +**Respuesta de error** (código 400): + +```json +{ + "error": "Invalid hero ID. ID must be a number." +} +``` + ## Manejo de Errores La API utiliza los siguientes códigos de estado HTTP: @@ -158,4 +194,10 @@ curl http://localhost:3000/api/heroes/1 ```bash curl http://localhost:3000/api/heroes?team=Justice&page=1&limit=2 +``` + +### Eliminar un héroe específico + +```bash +curl -X DELETE http://localhost:3000/api/heroes/1 ``` \ No newline at end of file diff --git a/docs/basic-usage.md b/docs/basic-usage.md index 637c41e..ccf9b52 100644 --- a/docs/basic-usage.md +++ b/docs/basic-usage.md @@ -131,6 +131,25 @@ La API proporciona los siguientes endpoints principales: - `PUT /api/heroes/:id`: Actualiza un héroe existente - `DELETE /api/heroes/:id`: Elimina un héroe por su ID +#### Eliminar un héroe por ID + +- **Endpoint**: `DELETE /api/heroes/:id` +- **Descripción**: Elimina un héroe específico de la base de datos +- **Parámetros de ruta**: + - `id`: ID numérico del héroe +- **Respuesta exitosa** (código 200): + ```json + { + "message": "Hero deleted successfully" + } + ``` +- **Respuesta de error** (código 404): + ```json + { + "error": "Hero not found" + } + ``` + ## Ejemplos de Uso ### Obtener todos los héroes @@ -177,6 +196,12 @@ curl http://localhost:3000/api/heroes?name=man&page=1&limit=3 curl http://localhost:3000/api/heroes/1 ``` +### Eliminar un héroe por ID + +```bash +curl -X DELETE http://localhost:3000/api/heroes/1 +``` + ## Próximos Pasos Para desarrollar en entornos más avanzados, consulta: diff --git a/heroes.http b/heroes.http index 9714d1d..bbee4dd 100644 --- a/heroes.http +++ b/heroes.http @@ -71,4 +71,7 @@ Content-Type: {{contentType}} "alterEgo": "Spider-Man", "powers": ["Wall-Crawling", "Spider-Sense", "Super Strength"], "team": "Avengers" -} \ No newline at end of file +} + +### Delete a hero by ID +DELETE {{baseUrl}}/heroes/1 HTTP/1.1 \ No newline at end of file diff --git a/src/controllers/hero.controller.ts b/src/controllers/hero.controller.ts index 721a7cb..4a4a061 100644 --- a/src/controllers/hero.controller.ts +++ b/src/controllers/hero.controller.ts @@ -1,5 +1,10 @@ import { Request, Response, NextFunction } from 'express'; -import { HeroService, HeroFilterOptions, CreateHeroResult } from '../services/hero.service.js'; +import { + HeroService, + HeroFilterOptions, + CreateHeroResult, + DeleteHeroResult, +} from '../services/hero.service.js'; import { Hero } from '../models/hero.model.js'; export class HeroController { @@ -141,4 +146,34 @@ export class HeroController { next(error); } } + + /** + * Delete a hero by ID + * @route DELETE /api/heroes/:id + * @param {number} id - Hero ID + * @returns {Object} Success message or error if not found + */ + async deleteHero(req: Request, res: Response, next: NextFunction): Promise { + try { + const id = Number(req.params.id); + + if (isNaN(id)) { + res.status(400).json({ error: 'Invalid hero ID. ID must be a number.' }); + return; + } + + const result: DeleteHeroResult = await this.heroService.deleteHeroById(id); + + if (!result.success) { + res.status(404).json({ error: result.error }); + return; + } + + res.status(200).json({ + message: 'Hero deleted successfully', + }); + } catch (error) { + next(error); + } + } } diff --git a/src/routes/hero.routes.ts b/src/routes/hero.routes.ts index 833ca6e..a92ea6f 100644 --- a/src/routes/hero.routes.ts +++ b/src/routes/hero.routes.ts @@ -8,5 +8,6 @@ const heroController = new HeroController(); router.get('/', (req, res, next) => heroController.getHeroes(req, res, next)); router.get('/:id', (req, res, next) => heroController.getHeroById(req, res, next)); router.post('/', (req, res, next) => heroController.createHero(req, res, next)); +router.delete('/:id', (req, res, next) => heroController.deleteHero(req, res, next)); export default router; diff --git a/src/services/hero.service.ts b/src/services/hero.service.ts index 6d83686..4b7da7e 100644 --- a/src/services/hero.service.ts +++ b/src/services/hero.service.ts @@ -26,6 +26,12 @@ export interface CreateHeroResult { error?: string; } +// Define interface for hero deletion result +export interface DeleteHeroResult { + success: boolean; + error?: string; +} + export class HeroService { /** * Get heroes from the database with filtering and pagination @@ -146,4 +152,32 @@ export class HeroService { }; } } + + /** + * Delete a hero by id from the database + * @param id Hero id to delete + * @returns Promise resolving to delete result with success flag and error if applicable + */ + async deleteHeroById(id: number): Promise { + try { + const deletedHero = await HeroModel.findOneAndDelete({ id }); + + if (!deletedHero) { + return { + success: false, + error: 'Hero not found', + }; + } + + return { + success: true, + }; + } catch (error) { + console.error(`Error deleting hero with id ${id}:`, error); + return { + success: false, + error: 'An unexpected error occurred while deleting the hero', + }; + } + } }