Skip to content

Instantly share code, notes, and snippets.

@Pyrolistical
Last active September 24, 2021 16:49
Show Gist options
  • Save Pyrolistical/b1870c1151713c9b2deed1c437d12635 to your computer and use it in GitHub Desktop.
Save Pyrolistical/b1870c1151713c9b2deed1c437d12635 to your computer and use it in GitHub Desktop.
type ApexLegendsGameResult = {
teamID: string,
placement: number,
kills: number
};
application.post('/apex-legends/:gameID/report-score', async ({params: {gameID}, body}, res) => {
await db.collection('apexLegendsGames').updateOne({
_id: gameID
}, {
$set: {
state: 'completed',
results: body as ApexLegendsGameResult[]
}
});
// signal to view service this document was updated
await views.documentUpdated({
collection: 'apexLegendsGames',
_id: gameID
});
return res.sendStatus(204);
});
const views = [
{
name: 'team stats table',
// dependencies resolve to the view params, in this case tournamentID
dependencies: {
async apexLegendsGames(gameID) {
const {tournamentID} = await db.collection('apexLegendsGames').findOne({
_id: gameID
});
return tournamentID;
},
async teams(teamID) {
const {tournamentID} = await db.collection('teams').findOne({
_id: teamID
});
return tournamentID;
}
},
async generate(tournamentID) {
const games = await db.collection('apexLegendsGames').find({
state: 'completed',
tournamentID
})
.toArray();
let totalKillsByTeamID = 0;
for (const {results} of games) {
for (const {teamID, kills} of results) {
totalKillsByTeamID[teamID] = totalKillsByTeamID[teamID] || {};
totalKillsByTeamID[teamID] += kills;
}
}
const teams = await db.collection('teams').find({
tournamentID
})
.toArray();
const teamByID = _.keyBy(teams, '_id');
await db.collection('teamStats').bulkWrite(teams.map(({_id: teamID}) => ({
updateOne: {
filter: {
tournamentID,
teamID
},
update: {
$set: {
teamName: teamByID[teamID].name,
totalKills: totalKillsByTeamID[teamID],
averageKills: totalKillsByTeamID[teamID] / results.length
}
},
upsert: true
}
})));
}
}
];
export async documentUpdated({collection, _id}) {
for (const {dependencies, generate} of views) {
const dependencyResolver = dependencies[collection];
if (dependencyResolver) {
await generate(dependencyResolver(_id));
}
}
}
application.get('/tournament/:tournamentID/team-stats', ({params: {tournamentID}, query: {sort, page}}, res) => {
const teamsPerPage = 10;
const pageIndex = page * teamsPerPage;
const page = db.collection('teamStats').find({
tournamentID
})
.sort({
[sort]: 1
})
.skip(pageIndex)
.limit(teamsPerPage)
.toArray();
return res.send(page);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment