38 lines
1.7 KiB
JavaScript
38 lines
1.7 KiB
JavaScript
const express = require('express')
|
|
const { listGames, getGameDetail, findGameById, favoriteGame, unfavoriteGame } = require('../db')
|
|
const { requireAuth } = require('../middleware/auth')
|
|
|
|
const router = express.Router()
|
|
|
|
router.get('/', async (req, res) => {
|
|
const games = await listGames(req.session?.userId || '', { includePrivate: !!req.session?.isAdmin })
|
|
res.json({ games, topics: games })
|
|
})
|
|
|
|
router.post('/:gameId/favorite', requireAuth, async (req, res) => {
|
|
const game = await findGameById(req.params.gameId)
|
|
if (!game || game.id === 'freeform') return res.status(404).json({ error: 'not_found' })
|
|
await favoriteGame({ userId: req.session.userId, gameId: game.id })
|
|
const games = await listGames(req.session.userId)
|
|
const updated = games.find((entry) => entry.id === game.id) || { ...game, isFavorited: true }
|
|
res.json({ game: updated, topic: updated })
|
|
})
|
|
|
|
router.delete('/:gameId/favorite', requireAuth, async (req, res) => {
|
|
const game = await findGameById(req.params.gameId)
|
|
if (!game || game.id === 'freeform') return res.status(404).json({ error: 'not_found' })
|
|
await unfavoriteGame({ userId: req.session.userId, gameId: game.id })
|
|
const games = await listGames(req.session.userId)
|
|
const updated = games.find((entry) => entry.id === game.id) || { ...game, isFavorited: false }
|
|
res.json({ game: updated, topic: updated })
|
|
})
|
|
|
|
router.get('/:gameId', async (req, res) => {
|
|
const detail = await getGameDetail(req.params.gameId)
|
|
if (!detail) return res.status(404).json({ error: 'not_found' })
|
|
if (!detail.game.isPublic && !req.session?.isAdmin) return res.status(404).json({ error: 'not_found' })
|
|
res.json({ game: detail.game, topic: detail.game, items: detail.items })
|
|
})
|
|
|
|
module.exports = router
|