Skip to main content

Get Tournament Metadata

The groupTournamentMeta method retrieves a list of all available tournaments for your game, including basic information like tournament names, types, and current status. This is typically the first call you make when implementing tournament functionality.

Overview

Use this method to:

  • Display a list of available tournaments to players
  • Check which tournaments are currently active
  • Get basic tournament information without detailed data
  • Determine which tournaments a player can join

Method Signature

MoitribeSDK(gameId, 'groupTournamentMeta', {
callback: (result) => {
// Handle response
}
});

Parameters

ParameterTypeRequiredDescription
callbackfunctionYesFunction to handle the response

Response Format

{
success: boolean;
tournaments: TournamentMeta[];
msg?: string; // Error message if success is false
}

interface TournamentMeta {
id: string; // Unique tournament identifier
name: string; // Display name for the tournament
description: string; // Brief description
type: string; // 'weekly', 'daily', 'special', 'seasonal'
status: string; // 'upcoming', 'active', 'ended', 'results'
startTime: number; // Tournament start timestamp (Unix)
endTime: number; // Tournament end timestamp (Unix)
maxParticipants?: number; // Maximum participants (if limited)
currentParticipants: number; // Current number of participants
prizePool?: string; // Prize description (if applicable)
}

JavaScript Example

// Get all available tournaments
MoitribeSDK('my-game-id', 'groupTournamentMeta', {
callback: (result) => {
if (result.success) {
console.log('Available tournaments:', result.tournaments);

// Display tournaments to player
result.tournaments.forEach((tournament) => {
console.log(`${tournament.name} - ${tournament.status}`);
console.log(`Starts: ${new Date(tournament.startTime)}`);
console.log(`Ends: ${new Date(tournament.endTime)}`);
console.log(`Participants: ${tournament.currentParticipants}`);
console.log('---');
});
} else {
console.error('Failed to get tournaments:', result.msg);
}
}
});

TypeScript Example

import MoitribeSDK from '@veniso/moitribe-js';

interface TournamentMeta {
id: string;
name: string;
description: string;
type: string;
status: string;
startTime: number;
endTime: number;
maxParticipants?: number;
currentParticipants: number;
prizePool?: string;
}

interface TournamentMetaResponse {
success: boolean;
tournaments: TournamentMeta[];
msg?: string;
}

// Get tournaments with proper typing
MoitribeSDK('my-game-id', 'groupTournamentMeta', {
callback: (result: TournamentMetaResponse) => {
if (result.success) {
// Filter active tournaments
const activeTournaments = result.tournaments.filter(
(tournament: TournamentMeta) => tournament.status === 'active'
);

console.log(`Found ${activeTournaments.length} active tournaments`);

// Display active tournaments
activeTournaments.forEach((tournament: TournamentMeta) => {
displayTournamentCard(tournament);
});
} else {
console.error('Error loading tournaments:', result.msg);
}
}
});

function displayTournamentCard(tournament: TournamentMeta) {
const card = document.createElement('div');
card.className = 'tournament-card';
card.innerHTML = `
<h3>${tournament.name}</h3>
<p>${tournament.description}</p>
<div class="tournament-info">
<span>Status: ${tournament.status}</span>
<span>Type: ${tournament.type}</span>
<span>Participants: ${tournament.currentParticipants}</span>
</div>
<div class="tournament-time">
<span>Ends: ${new Date(tournament.endTime).toLocaleDateString()}</span>
</div>
`;

card.addEventListener('click', () => {
// Handle tournament selection
selectTournament(tournament.id);
});

document.getElementById('tournaments-list').appendChild(card);
}

Common Use Cases

Display Tournament List

Show all available tournaments in a UI:

function loadTournamentList() {
MoitribeSDK('my-game-id', 'groupTournamentMeta', {
callback: (result) => {
if (result.success) {
const container = document.getElementById('tournaments-container');
container.innerHTML = '';

if (result.tournaments.length === 0) {
container.innerHTML = '<p>No tournaments available</p>';
return;
}

// Group tournaments by status
const grouped = groupTournamentsByStatus(result.tournaments);

// Display each group
Object.entries(grouped).forEach(([status, tournaments]) => {
const section = createTournamentSection(status, tournaments);
container.appendChild(section);
});
} else {
showError('Failed to load tournaments');
}
}
});
}

function groupTournamentsByStatus(tournaments) {
return tournaments.reduce((groups, tournament) => {
const status = tournament.status;
if (!groups[status]) {
groups[status] = [];
}
groups[status].push(tournament);
return groups;
}, {});
}

function createTournamentSection(status, tournaments) {
const section = document.createElement('div');
section.className = 'tournament-section';

const title = document.createElement('h2');
title.textContent = status.charAt(0).toUpperCase() + status.slice(1);
section.appendChild(title);

tournaments.forEach(tournament => {
const card = createTournamentCard(tournament);
section.appendChild(card);
});

return section;
}

Filter Active Tournaments

Get only tournaments that are currently running:

function getActiveTournaments() {
MoitribeSDK('my-game-id', 'groupTournamentMeta', {
callback: (result) => {
if (result.success) {
const now = Date.now();
const activeTournaments = result.tournaments.filter(tournament => {
return tournament.status === 'active' &&
tournament.startTime <= now &&
tournament.endTime > now;
});

if (activeTournaments.length > 0) {
showActiveTournaments(activeTournaments);
} else {
showNoActiveTournaments();
}
}
}
});
}

function showActiveTournaments(tournaments) {
const container = document.getElementById('active-tournaments');
container.innerHTML = '<h2>Active Tournaments</h2>';

tournaments.forEach(tournament => {
const timeLeft = tournament.endTime - Date.now();
const hoursLeft = Math.floor(timeLeft / (1000 * 60 * 60));

const card = document.createElement('div');
card.className = 'active-tournament';
card.innerHTML = `
<h3>${tournament.name}</h3>
<p>${tournament.description}</p>
<div class="tournament-stats">
<span>👥 ${tournament.currentParticipants} participants</span>
<span>⏰ ${hoursLeft} hours left</span>
</div>
<button onclick="joinTournament('${tournament.id}')">
Join Tournament
</button>
`;

container.appendChild(card);
});
}

Tournament Countdown

Show countdown timers for upcoming tournaments:

function loadUpcomingTournaments() {
MoitribeSDK('my-game-id', 'groupTournamentMeta', {
callback: (result) => {
if (result.success) {
const upcoming = result.tournaments.filter(
tournament => tournament.status === 'upcoming'
);

upcoming.forEach(tournament => {
startCountdown(tournament);
});
}
}
});
}

function startCountdown(tournament) {
const countdownElement = document.getElementById(`countdown-${tournament.id}`);

function updateCountdown() {
const now = Date.now();
const startTime = tournament.startTime;
const timeLeft = startTime - now;

if (timeLeft <= 0) {
countdownElement.textContent = 'Starting now!';
// Refresh tournament list
loadTournamentList();
return;
}

const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));

countdownElement.textContent = `${days}d ${hours}h ${minutes}m`;

setTimeout(updateCountdown, 60000); // Update every minute
}

updateCountdown();
}

Tournament Type Filtering

Filter tournaments by type:

function loadTournamentsByType(type) {
MoitribeSDK('my-game-id', 'groupTournamentMeta', {
callback: (result) => {
if (result.success) {
const filteredTournaments = result.tournaments.filter(
tournament => tournament.type === type
);

displayTournaments(filteredTournaments, `${type} Tournaments`);
}
}
});
}

// Example usage
document.getElementById('btn-weekly').onclick = () => loadTournamentsByType('weekly');
document.getElementById('btn-daily').onclick = () => loadTournamentsByType('daily');
document.getElementById('btn-special').onclick = () => loadTournamentsByType('special');

Error Handling

Handle common errors when retrieving tournament metadata:

MoitribeSDK('my-game-id', 'groupTournamentMeta', {
callback: (result) => {
if (result.success) {
// Process tournaments
processTournaments(result.tournaments);
} else {
// Handle specific error cases
if (result.msg.includes('network')) {
showError('Network error. Please check your connection.');
} else if (result.msg.includes('unauthorized')) {
showError('Please log in to view tournaments.');
} else if (result.msg.includes('maintenance')) {
showError('Tournament system is under maintenance.');
} else {
showError('Failed to load tournaments. Please try again.');
}

// Retry logic
setTimeout(() => {
console.log('Retrying tournament load...');
loadTournamentList();
}, 5000);
}
}
});

Best Practices

Caching Strategy

Cache tournament metadata to reduce API calls:

class TournamentManager {
constructor() {
this.cache = null;
this.cacheTime = 0;
this.cacheDuration = 5 * 60 * 1000; // 5 minutes
}

async getTournaments() {
const now = Date.now();

// Return cached data if still valid
if (this.cache && (now - this.cacheTime) < this.cacheDuration) {
return this.cache;
}

// Fetch fresh data
return new Promise((resolve, reject) => {
MoitribeSDK('my-game-id', 'groupTournamentMeta', {
callback: (result) => {
if (result.success) {
this.cache = result.tournaments;
this.cacheTime = now;
resolve(result.tournaments);
} else {
reject(new Error(result.msg));
}
}
});
});
}
}

const tournamentManager = new TournamentManager();

// Usage
tournamentManager.getTournaments()
.then(tournaments => {
console.log('Tournaments loaded:', tournaments);
})
.catch(error => {
console.error('Failed to load tournaments:', error);
});

Real-time Updates

Periodically refresh tournament data:

let refreshInterval;

function startTournamentRefresh() {
// Initial load
loadTournamentList();

// Refresh every 2 minutes
refreshInterval = setInterval(() => {
loadTournamentList();
}, 2 * 60 * 1000);
}

function stopTournamentRefresh() {
if (refreshInterval) {
clearInterval(refreshInterval);
}
}

// Start when page loads
window.addEventListener('load', startTournamentRefresh);
window.addEventListener('beforeunload', stopTournamentRefresh);

Next Steps

After retrieving tournament metadata:

Related topics: