Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions docs/basic-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,41 @@ 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

- **Endpoint**: `DELETE /api/heroes/:id`
- **Descripción**: Elimina un héroe específico de la base de datos (solo para casos justificados)
- **Parámetros de ruta**:
- `id`: ID numérico del héroe
- **Parámetros de consulta**:
- `confirm`: Booleano (true/false) que confirma explícitamente la intención de eliminar
- **Respuesta exitosa** (código 200):
```json
{
"success": true,
"message": "Hero Superman has been deleted"
}
```
- **Respuestas de error**:
- Sin confirmación (código 400):
```json
{
"error": "Confirmation is required to delete a hero"
}
```
- Héroe no encontrado (código 404):
```json
{
"error": "Hero with ID 999 not found"
}
```
- Error del servidor (código 500):
```json
{
"error": "An unexpected error occurred while deleting the hero"
}
```

## Ejemplos de Uso

### Obtener todos los héroes
Expand Down Expand Up @@ -177,6 +212,12 @@ curl http://localhost:3000/api/heroes?name=man&page=1&limit=3
curl http://localhost:3000/api/heroes/1
```

### Eliminar un héroe (con confirmación)

```bash
curl -X DELETE http://localhost:3000/api/heroes/1?confirm=true
```

## Próximos Pasos

Para desarrollar en entornos más avanzados, consulta:
Expand Down
11 changes: 10 additions & 1 deletion heroes.http
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,13 @@ Content-Type: {{contentType}}
"alterEgo": "Spider-Man",
"powers": ["Wall-Crawling", "Spider-Sense", "Super Strength"],
"team": "Avengers"
}
}

### Delete hero without confirmation (will fail)
DELETE {{baseUrl}}/heroes/1 HTTP/1.1
Copy link
Preview

Copilot AI May 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test request path is missing the /api prefix; it should be {{baseUrl}}/api/heroes/1 to match the configured route.

Copilot uses AI. Check for mistakes.


### Delete hero with confirmation
DELETE {{baseUrl}}/heroes/1?confirm=true HTTP/1.1

### Delete non-existent hero (will fail)
DELETE {{baseUrl}}/heroes/999?confirm=true HTTP/1.1
40 changes: 40 additions & 0 deletions src/controllers/hero.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,44 @@ export class HeroController {
next(error);
}
}

/**
* Delete a hero by ID
* @route DELETE /api/heroes/:id
* @param {number} id - Hero ID
* @query {boolean} confirm - Confirmation flag to ensure deletion is intentional
* @returns {Object} Success message or error message
*/
async deleteHero(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const id = Number(req.params.id);
const confirm = req.query.confirm === 'true';

if (isNaN(id)) {
res.status(400).json({ error: 'Invalid hero ID. ID must be a number.' });
return;
}

const result = await this.heroService.deleteHero(id, confirm);

if (!result.success) {
// Determine appropriate status code based on error
if (result.error === 'Confirmation is required to delete a hero') {
res.status(400).json({ error: result.error });
} else if (result.error?.includes('not found')) {
res.status(404).json({ error: result.error });
} else {
res.status(500).json({ error: result.error });
Comment on lines +165 to +171
Copy link
Preview

Copilot AI May 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Matching on exact error message content is brittle; consider extending DeleteHeroResult with a status code or error code enum to drive HTTP status decisions.

Suggested change
// Determine appropriate status code based on error
if (result.error === 'Confirmation is required to delete a hero') {
res.status(400).json({ error: result.error });
} else if (result.error?.includes('not found')) {
res.status(404).json({ error: result.error });
} else {
res.status(500).json({ error: result.error });
// Determine appropriate status code based on errorCode
switch (result.errorCode) {
case 'INVALID_CONFIRMATION':
res.status(400).json({ error: 'Confirmation is required to delete a hero' });
break;
case 'HERO_NOT_FOUND':
res.status(404).json({ error: 'Hero not found' });
break;
default:
res.status(500).json({ error: 'An unknown error occurred' });

Copilot uses AI. Check for mistakes.

}
return;
}

res.status(200).json({
success: true,
message: result.message,
});
} catch (error) {
next(error);
}
}
}
1 change: 1 addition & 0 deletions src/routes/hero.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
51 changes: 51 additions & 0 deletions src/services/hero.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ export interface CreateHeroResult {
error?: string;
}

// Define interface for hero deletion result
export interface DeleteHeroResult {
success: boolean;
message?: string;
error?: string;
}

export class HeroService {
/**
* Get heroes from the database with filtering and pagination
Expand Down Expand Up @@ -146,4 +153,48 @@ export class HeroService {
};
}
}

/**
* Delete a hero from the database
* @param id Hero id to delete
* @param confirm Confirmation flag to ensure deletion is intentional
* @returns Promise resolving to delete result with success flag and message or error
*/
async deleteHero(id: number, confirm: boolean): Promise<DeleteHeroResult> {
try {
// Check if confirmation is provided
if (!confirm) {
return {
success: false,
error: 'Confirmation is required to delete a hero',
};
}

// Check if hero exists
const hero = await HeroModel.findOne({ id });
if (!hero) {
return {
success: false,
error: `Hero with ID ${id} not found`,
};
}

// Delete the hero
await HeroModel.deleteOne({ id });

// Log the deletion for audit purposes
console.log(`Hero deleted: ${hero.name} (ID: ${id}) at ${new Date().toISOString()}`);
Copy link
Preview

Copilot AI May 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using the project's structured logger instead of console.log for audit logging to maintain consistency and enable log level control.

Copilot uses AI. Check for mistakes.


return {
success: true,
message: `Hero ${hero.name} has been deleted`,
};
} catch (error) {
console.error(`Error deleting hero with id ${id}:`, error);
Copy link
Preview

Copilot AI May 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using the project's structured logger instead of console.error for error logging to maintain consistency and facilitate log aggregation.

Suggested change
console.error(`Error deleting hero with id ${id}:`, error);
logger.error(`Error deleting hero with id ${id}:`, { id, error });

Copilot uses AI. Check for mistakes.

return {
success: false,
error: 'An unexpected error occurred while deleting the hero',
};
}
}
}
Loading