import { database, Character, Game, Pick, App } from './db' import { OrderByParser, FilterParser, ParsingError } from './tokenizer' export function addCharacterApis(app, jsonParser, memcace) { app.get('/api/character/:characterId', async (req, res) => { try { const character = await Character.findOne({ attributes: ['id', 'characterName', 'playerName', 'role', 'creationDate', 'status'], 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 || 10 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 totalCount = await Character.count({ where: filter }) const pageCount = Math.ceil(totalCount / count) res.setHeader('Content-Type', 'application/json') res.send({ characterData, pageCount, totalCount }) } 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) } }) }