|
| 1 | +import { NextFunction, Request, Response } from "express"; |
| 2 | +import * as achievementService from "../services/achievement.service"; |
| 3 | +import { ApiError } from "../utils/apiError"; |
| 4 | + |
| 5 | +export const getAchievements = async (req: Request, res: Response, next: NextFunction) => { |
| 6 | + const achievements = await achievementService.getAchievements(); |
| 7 | + |
| 8 | + if (!achievements || achievements.length === 0) { |
| 9 | + throw new ApiError("No achievements found", 404); |
| 10 | + } |
| 11 | + |
| 12 | + res.status(200).json({ |
| 13 | + success: true, |
| 14 | + count: achievements.length, |
| 15 | + data: achievements, |
| 16 | + }); |
| 17 | +}; |
| 18 | + |
| 19 | + |
| 20 | +export const getAchievementById = async (req: Request, res: Response, next: NextFunction) => { |
| 21 | + const achievementId = parseInt(req.params.achievementId); |
| 22 | + |
| 23 | + const achievement = await achievementService.getAchievementById(achievementId); |
| 24 | + |
| 25 | + if (!achievement) { |
| 26 | + throw new ApiError("Achievement not found", 404); |
| 27 | + } |
| 28 | + |
| 29 | + res.status(200).json({ |
| 30 | + success: true, |
| 31 | + data: achievement, |
| 32 | + }); |
| 33 | +}; |
| 34 | + |
| 35 | + |
| 36 | +export const updateAchievementById = async (req: Request, res: Response, next: NextFunction) => { |
| 37 | + const achievementId = parseInt(req.params.achievementId); |
| 38 | + |
| 39 | + if (!achievementId) { |
| 40 | + throw new ApiError("Invalid achievement ID", 400); |
| 41 | + } |
| 42 | + |
| 43 | + const { title, achievedAt, imageUrl} = req.body; |
| 44 | + |
| 45 | + const existingAchievement = await achievementService.getAchievementById(achievementId); |
| 46 | + |
| 47 | + if (!existingAchievement) { |
| 48 | + throw new ApiError("Achievement not found", 404); |
| 49 | + } |
| 50 | + |
| 51 | + const updatedAchievement = await achievementService.updateAchievementById(achievementId, { |
| 52 | + title, |
| 53 | + achievedAt, |
| 54 | + imageUrl, |
| 55 | + }); |
| 56 | + |
| 57 | + res.status(200).json({ |
| 58 | + success: true, |
| 59 | + data: updatedAchievement, |
| 60 | + }); |
| 61 | +}; |
| 62 | + |
| 63 | + |
| 64 | +export const deleteAchievementById = async (req: Request, res: Response, next: NextFunction) => { |
| 65 | + const achievementId = parseInt(req.params.achievementId); |
| 66 | + |
| 67 | + const existingAchievement = await achievementService.getAchievementById(achievementId); |
| 68 | + |
| 69 | + if (!existingAchievement) { |
| 70 | + throw new ApiError("Achievement not found", 404); |
| 71 | + } |
| 72 | + |
| 73 | + await achievementService.deleteAchievementById(achievementId); |
| 74 | + |
| 75 | + res.status(200).json({ |
| 76 | + success: true, |
| 77 | + message: "Achievement deleted successfully", |
| 78 | + }); |
| 79 | +}; |
| 80 | + |
0 commit comments