diff --git a/.gitignore b/.gitignore index 2309cc8..ba808b4 100644 --- a/.gitignore +++ b/.gitignore @@ -136,3 +136,4 @@ dist .yarn/install-state.gz .pnp.* +.vscode/ \ No newline at end of file diff --git a/controllers/gameController.js b/controllers/gameController.js index 07ce948..103e3a3 100644 --- a/controllers/gameController.js +++ b/controllers/gameController.js @@ -320,6 +320,79 @@ class GameController { } } + /** + * Create or Update game with URL check + * Nếu body có id: update game đó + * Nếu body không có id: kiểm tra URL có tồn tại trong DB không, chưa có thì lưu mới + */ + async createGameWithUrlCheck(req, res, next) { + try { + const { + id, + title, + description, + url, + thumbnail, + type, + config, + is_active, + is_premium, + min_grade, + max_grade, + difficulty_level, + display_order, + rating, + } = req.body; + + // Validate required fields + if (!title || !url || !type) { + return res.status(400).json({ + success: false, + message: 'title, url, and type are required', + }); + } + + // Check if URL already exists in DB + const existingGame = await Game.findOne({ where: { url } }); + if (existingGame) { + return res.status(200).json({ + success: true, + data: null, + message: 'URL đã tồn tại, game không được lưu', + }); + } + + // Create new game (with id if provided, or auto-generate) + const game = await Game.create({ + ...(id && { id }), + title, + description, + url, + thumbnail, + type, + config: config || {}, + is_active: is_active !== undefined ? is_active : true, + is_premium: is_premium !== undefined ? is_premium : false, + min_grade, + max_grade, + difficulty_level, + display_order: display_order || 0, + play_count: 0, + }); + + // Clear cache + await cacheUtils.deletePattern('games:*'); + + res.status(201).json({ + success: true, + data: game, + message: 'Game created successfully', + }); + } catch (error) { + next(error); + } + } + /** * Get game statistics */ diff --git a/routes/gameRoutes.js b/routes/gameRoutes.js index ceba2fe..312f16d 100644 --- a/routes/gameRoutes.js +++ b/routes/gameRoutes.js @@ -22,6 +22,9 @@ router.get('/:id', gameController.getGameById); // Create new game router.post('/', gameController.createGame); +// Create new game with URL validation (check if URL exists before saving) +router.post('/save-with-check', gameController.createGameWithUrlCheck); + // Update game router.put('/:id', gameController.updateGame);