C
CoderspaE
/Documentation

CoderspaE SDK

Official Software Development Kit for CoderspaE platform integration

SDK Overview

The CoderspaE SDK provides a comprehensive interface to interact with the CoderspaE platform programmatically. Build custom applications, integrations, and tools with our battle-tested API.

🚀 High Performance

Optimized for speed with built-in caching and connection pooling

🔒 Type Safe

Full TypeScript support with generated types from API schema

📡 Real-time

WebSocket support for live battles and real-time updates

Quick Start

Installation

npm install @coderspae/sdk
# or
yarn add @coderspae/sdk
# or
pnpm add @coderspae/sdk

Basic Setup

import { CoderspaE } from '@coderspae/sdk';

// Initialize the client
const client = new CoderspaE({
  apiKey: process.env.CODERSPAE_API_KEY,
  environment: 'production', // or 'development'
  timeout: 30000 // optional, defaults to 30s
});

// Basic usage
const user = await client.users.getCurrent();
console.log('Welcome,', user.username);

Core Features

⚔️ Battle Management

// Create a battle
const battle = await client.battles.create({
  type: 'quick',
  difficulty: 'medium',
  language: 'javascript'
});

// Join a battle
await client.battles.join(battle.id);

// Submit solution
await client.battles.submit({
  battleId: battle.id,
  code: 'function solve(input) {...}',
  language: 'javascript'
});

// Get battle results
const results = await client.battles.getResults(battle.id);

🏆 Tournament System

// List tournaments
const tournaments = await client.tournaments.list({
  status: 'upcoming',
  limit: 10
});

// Register for tournament
await client.tournaments.register(tournamentId);

// Get tournament leaderboard
const leaderboard = await client.tournaments.getLeaderboard({
  tournamentId,
  live: true
});

// Stream tournament updates
client.tournaments.stream(tournamentId, (update) => {
  console.log('Tournament update:', update);
});

👥 Team Operations

// Create team
const team = await client.teams.create({
  name: 'Code Warriors',
  description: 'Elite coding team',
  isPublic: true
});

// Invite members
await client.teams.invite({
  teamId: team.id,
  username: 'developer123'
});

// Start team battle
const teamBattle = await client.teams.createBattle({
  teamId: team.id,
  opponentTeamId: 'other-team-id'
});

📊 Analytics & Stats

// User statistics
const stats = await client.analytics.getUserStats({
  userId: 'current',
  timeframe: 'last_30_days'
});

// Performance metrics
const metrics = await client.analytics.getPerformanceMetrics({
  userId: 'current',
  category: 'algorithms'
});

// Leaderboard position
const ranking = await client.leaderboards.getUserRank({
  userId: 'current',
  type: 'global'
});

Real-time Features

WebSocket Connections

// Connect to real-time events
const socket = client.connect();

// Listen for battle updates
socket.on('battle:update', (data) => {
  console.log('Battle progress:', data.progress);
  console.log('Participants:', data.participants);
});

// Listen for new challenges
socket.on('challenge:received', (challenge) => {
  console.log('New challenge from:', challenge.challenger.username);
});

// Join battle room for live updates
socket.joinBattle(battleId);

// Get typing indicators during battles
socket.on('battle:typing', (data) => {
  console.log(`${data.username} is typing...`);
});

// Disconnect when done
socket.disconnect();

Configuration Options

const client = new CoderspaE({
  // Required
  apiKey: 'your-api-key',
  
  // Environment
  environment: 'production', // 'development' | 'staging' | 'production'
  baseURL: 'https://api.coderspae.com', // custom API endpoint
  
  // Timeouts
  timeout: 30000, // request timeout in ms
  retryTimeout: 5000, // retry delay in ms
  maxRetries: 3, // max retry attempts
  
  // Rate limiting
  rateLimit: {
    requests: 1000, // requests per window
    window: 3600000 // window in ms (1 hour)
  },
  
  // Real-time
  websocket: {
    autoConnect: true, // auto-connect WebSocket
    reconnect: true, // auto-reconnect on disconnect
    heartbeat: 30000 // heartbeat interval in ms
  },
  
  // Caching
  cache: {
    enabled: true,
    ttl: 300000, // cache TTL in ms (5 minutes)
    maxSize: 1000 // max cache entries
  },
  
  // Debugging
  debug: false, // enable debug logging
  logLevel: 'info' // 'debug' | 'info' | 'warn' | 'error'
});

Error Handling

import { CoderspaEError, APIError, RateLimitError } from '@coderspae/sdk';

try {
  const battle = await client.battles.create({
    type: 'quick',
    difficulty: 'hard'
  });
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log('Rate limit exceeded. Retry after:', error.retryAfter);
  } else if (error instanceof APIError) {
    console.log('API Error:', error.message);
    console.log('Status:', error.status);
    console.log('Code:', error.code);
  } else if (error instanceof CoderspaEError) {
    console.log('SDK Error:', error.message);
  } else {
    console.log('Unknown error:', error);
  }
}

// Global error handler
client.on('error', (error) => {
  console.error('SDK Error:', error);
});

// Rate limit warnings
client.on('rateLimitWarning', (info) => {
  console.warn('Approaching rate limit:', info);
});

TypeScript Support

The SDK is built with TypeScript and provides full type safety for all API interactions.

import { 
  CoderspaE, 
  Battle, 
  Tournament, 
  User, 
  BattleType,
  Difficulty 
} from '@coderspae/sdk';

// Typed responses
const battle: Battle = await client.battles.create({
  type: 'quick' as BattleType,
  difficulty: 'medium' as Difficulty
});

// Typed parameters with intellisense
const tournaments: Tournament[] = await client.tournaments.list({
  status: 'active', // autocomplete available
  limit: 50
});

// Custom type guards
function isBattleComplete(battle: Battle): battle is CompletedBattle {
  return battle.status === 'completed';
}

// Generic type support
const userStats = await client.analytics.getUserStats<DetailedStats>({
  userId: 'current',
  includeDetails: true
});

Advanced Usage

Custom Middleware

// Add request middleware
client.use('request', async (req, next) => {
  req.headers['X-Custom-Header'] = 'value';
  console.log('Making request to:', req.url);
  return next(req);
});

// Add response middleware
client.use('response', async (res, next) => {
  console.log('Response status:', res.status);
  return next(res);
});

// Add error middleware
client.use('error', async (error, next) => {
  console.error('Request failed:', error.message);
  // Custom error handling
  if (error.status === 429) {
    await new Promise(resolve => setTimeout(resolve, 5000));
    return error.retry();
  }
  return next(error);
});

Batch Operations

// Batch API calls
const batch = client.batch();

batch.add('user', client.users.getCurrent());
batch.add('stats', client.analytics.getUserStats());
batch.add('battles', client.battles.list({ limit: 5 }));

const results = await batch.execute();

console.log('User:', results.user);
console.log('Stats:', results.stats);
console.log('Recent battles:', results.battles);

// Parallel execution with error handling
const [user, tournaments, teams] = await Promise.allSettled([
  client.users.getCurrent(),
  client.tournaments.list(),
  client.teams.list()
]);

Migration Guide

From REST API to SDK

Before (REST API)

const response = await fetch('https://api.coderspae.com/battles', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    type: 'quick',
    difficulty: 'medium'
  })
});

const battle = await response.json();

After (SDK)

const battle = await client.battles.create({
  type: 'quick',
  difficulty: 'medium'
});