81 lines
2.2 KiB
TypeScript
81 lines
2.2 KiB
TypeScript
import { database, Character, Game, Pick, App } from './db'
|
|
import { OrderByParser, FilterParser, ParsingError } from './tokenizer'
|
|
|
|
export function addGameApis(app, jsonParser) {
|
|
app.get('/api/game/:gameId', async (req, res) => {
|
|
try {
|
|
const game = await Game.findOne({ where: { id: req.params['gameId'] } })
|
|
if (!game) {
|
|
res.status(404).send('Game Not Found')
|
|
} else {
|
|
res.send(game)
|
|
}
|
|
} catch (e) {
|
|
console.log(e)
|
|
res.status(500).send(e)
|
|
}
|
|
})
|
|
|
|
app.post('/api/game', jsonParser, async (req, res) => {
|
|
try {
|
|
const fp = new FilterParser()
|
|
const obp = new OrderByParser()
|
|
const page = req.body.page || 0
|
|
const orderBy = req.body.orderBy ? obp.parse(req.body.orderBy) : ['id']
|
|
const count = req.body.count || 10
|
|
const filter = req.body.filter ? fp.parse(req.body.filter) : {}
|
|
|
|
const gameData = await Game.findAll({
|
|
offset: page * count,
|
|
limit: count,
|
|
order: orderBy,
|
|
where: filter
|
|
})
|
|
const pageCount = Math.ceil(
|
|
(await Game.count({
|
|
where: filter
|
|
})) / count
|
|
)
|
|
|
|
res.setHeader('Content-Type', 'application/json')
|
|
res.send({ gameData, pageCount })
|
|
} catch (e) {
|
|
if (e instanceof ParsingError) {
|
|
res.status(400).send('Could not parse filter.')
|
|
} else {
|
|
res.status(500).send(e)
|
|
}
|
|
}
|
|
})
|
|
|
|
app.post('/api/game/:gameId/apps', async (req, res) => {
|
|
try {
|
|
const apps = await App.findAll({
|
|
include: { model: Character, as: "appliedCharacter"},
|
|
where: { gameId: req.params['gameId'] } })
|
|
if (!apps) {
|
|
res.status(404).send('Apps not found.')
|
|
} else {
|
|
res.send(apps)
|
|
}
|
|
} catch (e) {
|
|
res.status(500).send(e)
|
|
}
|
|
})
|
|
|
|
app.post('/api/game/:gameId/picks', async (req, res) => {
|
|
try {
|
|
const picks = await Pick.findAll({
|
|
include: { model: Character, as: "pickedCharacter"},
|
|
where: { gameId: req.params['gameId'] } })
|
|
if (!picks) {
|
|
res.status(404).send('Picks not found')
|
|
} else {
|
|
res.send(picks)
|
|
}
|
|
} catch (e) {
|
|
res.status(500).send(e)
|
|
}
|
|
})
|
|
}
|