Skip to content

Instantly share code, notes, and snippets.

@Strift
Last active November 26, 2021 16:20
Show Gist options
  • Save Strift/17a89894764f1e28ce1a2efa4b6a2a93 to your computer and use it in GitHub Desktop.
Save Strift/17a89894764f1e28ce1a2efa4b6a2a93 to your computer and use it in GitHub Desktop.
Example of PandaScore tournament brackets API consumption
import { fetchMatches, formatAsTree } from './tournament'
async function main() {
const matchesData = await fetchMatches(LCS_PROVING_GROUNDS_PLAYOFFS_ID)
bracketTree = formatAsTree(matchesData)
console.log(bracketTree)
}
main()
import axios from 'axios' // https://github.com/axios/axios
import { DateTime } from 'luxon' // https://moment.github.io/luxon/
const API_TOKEN = '<insert your API token>'
const http = axios.create({
baseURL: 'https://api.pandascore.co',
headers: {
Authorization: `Bearer ${API_TOKEN}`
}
})
/**
* Fetches matches from the tournament brackets endpoint
* @param {number} tournamentId ID of the tournament
* @returns {Promise<Array>} Array of matches with `previous_matches` array
*/
export async function fetchMatches (tournamentId) {
const { data } = await http.get(`/tournaments/${tournamentId}/brackets`)
return data
}
/**
* Creates and return a binary tree where each node represents the winner or loser of a match
* @param {Array} matches Array of matches
* @returns {Object} A binary tree
*/
export function formatAsTree (matches) {
// Sort matches for easier Finals access
const orderedMatches = sortInReverseChronologicalOrder(matches)
const findMatchById = (matchId) => orderedMatches.find(({ id }) => id === matchId)
const buildMatchTree = (match, previousType) => {
if (!match) {
return {}
}
const treeNode = {
id: match.id,
name: match.name,
type: previousType
}
// If the node represents a match loser, we should not continue building this branch
// Because the match already appears in the winner bracket
if (treeNode.type !== 'loser') {
if (match.previous_matches.length) {
treeNode.prevLeft = buildMatchTree(findMatchById(match.previous_matches[0].match_id), match.previous_matches[0].type)
}
if (match.previous_matches.length === 2) {
treeNode.prevRight = buildMatchTree(findMatchById(match.previous_matches[1].match_id), match.previous_matches[1].type)
}
}
return treeNode
}
return buildMatchTree(orderedMatches[0])
}
/**
* Sort matches by `scheduled_at` in reverse order
* @param {Array} matches Array of matches
* @returns {Array} Array of matches
*/
function sortInReverseChronologicalOrder (matches) {
return matches.sort((matchA, matchB) => {
return DateTime.fromISO(matchB.scheduled_at).toMillis() - DateTime.fromISO(matchA.scheduled_at).toMillis()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment