work on relational models. get a characters game history

This commit is contained in:
jmosrael@gmail.com
2024-05-12 18:16:40 -07:00
parent ddef1d8e4d
commit e61d0e6474
2 changed files with 34 additions and 5 deletions

View File

@@ -62,6 +62,24 @@ const App = sequelize.define(
{ timestamps: false }
)
// Bind characters to applications and picks
Character.hasMany(App, { foreignKey: 'characterId', as: 'appliedCharacter' })
App.belongsTo(Character, { foreignKey: 'characterId', as: 'appliedCharacter' })
Character.hasMany(Pick, { foreignKey: 'characterId', as: 'pickedCharacter' })
Pick.belongsTo(Character, { foreignKey: 'characterId', as: 'pickedCharacter' })
// Bind games to applications and picks
Game.hasMany(App, { foreignKey: 'gameId', as: 'gameApplications' })
App.belongsTo(Game, { foreignKey: 'gameId', as: 'gameApplications' })
Game.hasMany(Pick, { foreignKey: 'gameId', as: 'gamePicks' })
Pick.belongsTo(Game, { foreignKey: 'gameId', as: 'gamePicks' })
// Bind picked characters to games.
Game.belongsToMany(Character, { through: 'Apps', as: 'characterAppliedForGame' })
Character.belongsToMany(Game, { through: 'Apps', as: 'characterAppliedForGame' })
Game.belongsToMany(Character, { through: 'Picks', as: 'characterPickedForGame' })
Character.belongsToMany(Game, { through: 'Picks', as: 'characterPickedForGame' })
const app = express()
const jsonParser = json()
const port = 3001
@@ -89,8 +107,8 @@ app.post('/api/character', jsonParser, async (req, res) => {
res.json({ characterData, pageCount })
})
app.get('/api/game/:characterId', async (req, res) => {
res.send(await Game.findOne({ where: { id: req.params['characterId'] } }))
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) => {
@@ -136,6 +154,17 @@ app.post('/api/character/:characterId/picks', async (req, res) => {
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 sequelize.authenticate()
return console.log(`Express is listening at http://localhost:${port}`)

View File

@@ -20,10 +20,10 @@ const character = ref({})
async function loadCharacterDetails() {
const characterResponse = await axios.get(`/api/character/${characterId.value}`)
const gameDetails = await axios.post("/api/game", {
})
const gameDetails = await axios.post(`/api/character/${characterId.value}/gameHistory`)
console.log(characterResponse)
console.log(gameDetails)
character.value = characterResponse.data
}