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,97 @@
import { database, Character, Game, Pick, App } from './db'
import { OrderByParser, FilterParser, ParsingError } from './tokenizer'
export function addCharacterApis(app, jsonParser) {
app.get('/api/character/:characterId', async (req, res) => {
try {
const character = await Character.findOne({
where: { id: req.params['characterId'] }
})
if (character) {
res.send(character)
} else {
res.status(404).send('Cannot find character.')
}
} catch (e) {
res.status(500).send(e)
}
})
app.post('/api/character', jsonParser, async (req, res) => {
try {
const fp = new FilterParser()
const obp = new OrderByParser()
const page = req.body.page
const orderBy = req.body.orderBy ? obp.parse(req.body.orderBy) : ['id']
const count = req.body.count
const filter = req.body.filter ? fp.parse(req.body.filter) : {}
const characterData = await Character.findAll({
offset: page * count,
limit: count,
order: orderBy,
where: filter
})
const pageCount = Math.ceil(
(await Character.count({
where: filter
})) / count
)
res.setHeader('Content-Type', 'application/json')
res.send({ characterData, pageCount })
} catch (e) {
if (e instanceof ParsingError) {
res.status(400).send('Could not parse filter.')
} else {
res.status(500).send(e)
}
}
})
app.post('/api/character/:characterId/apps', async (req, res) => {
try {
const apps = await App.findAll({ where: { characterId: req.params['characterId'] } })
if (apps) {
res.send(apps)
} else {
res.status(400).send('Could not find apps.')
}
} catch (e) {
res.status(500).send(e)
}
})
app.post('/api/character/:characterId/picks', async (req, res) => {
try {
const picks = await Pick.findAll({ where: { characterId: req.params['characterId'] } })
if (picks) {
res.send(picks)
} else {
res.status(400).send('Could not find picks.')
}
} catch (e) {
res.status(500).send(e)
}
})
app.post('/api/character/:characterId/gameHistory', async (req, res) => {
try {
const gameHistory = await Character.findOne({
include: [
{ model: Game, as: 'characterPickedForGame' },
{ model: Game, as: 'characterAppliedForGame' }
],
where: { id: req.params['characterId'] }
})
if (gameHistory) {
res.send(gameHistory)
} else {
res.status(404).send("Could nor find character.")
}
} catch (e) {
res.status(500).send(e)
}
})
}