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