Add in erro handeling forback end

This commit is contained in:
jmosrael@gmail.com
2024-05-26 19:28:01 -07:00
parent e62825a114
commit 5890041501
4 changed files with 185 additions and 97 deletions

View File

@@ -0,0 +1,76 @@
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({ 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({ 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)
}
})
}