import express from 'express' import { json } from 'body-parser' import { Sequelize, Op } from 'sequelize' import { database, Character, Game, Pick, App } from './db' import { OrderByParser, FilterParser } from './tokenizer' const app = express() const jsonParser = json() const fp = new FilterParser() const obp = new OrderByParser() const port = 3001 app.get('/', (req, res) => { res.send('Hello World!') }) app.get('/api/character/:characterId', async (req, res) => { res.send(await Character.findOne({ where: { id: req.params['characterId'] } })) }) app.post('/api/character', jsonParser, async (req, res) => { 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.json({ characterData, pageCount }) }) app.get('/api/game/:gameId', async (req, res) => { res.send(await Game.findOne({ where: { id: req.params['gameId'] } })) }) app.post('/api/game', jsonParser, async (req, res) => { 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 }) }) app.get('/api/game/:gameId', async (req, res) => { const game = await Game.findOne({ where: { id: req.params['gameId'] } }) res.send(game) }) app.post('/api/game/:gameId/apps', async (req, res) => { const apps = await App.findAll({ where: { gameId: req.params['gameId'] } }) res.send(apps) }) app.post('/api/character/:characterId/apps', async (req, res) => { const apps = await App.findAll({ where: { characterId: req.params['characterId'] } }) res.send(apps) }) app.post('/api/game/:gameId/picks', async (req, res) => { const picks = await Pick.findAll({ where: { gameId: req.params['gameId'] } }) res.send(picks) }) app.post('/api/character/:characterId/picks', async (req, res) => { const picks = await Pick.findAll({ where: { characterId: req.params['characterId'] } }) res.send(picks) }) app.post('/api/character/:characterId/gameHistory', async (req, res) => { const gameHistory = await Character.findOne({ include: [ { model: Game, as: 'characterPickedForGame' }, { model: Game, as: 'characterAppliedForGame' } ], where: { id: req.params['characterId'] } }) res.send(gameHistory) }) app.listen(port, async () => { await database.authenticate() return console.log(`Express is listening at http://localhost:${port}`) })