Skip to content
J03Fr0stPublic

About

A typescript wrapper for the PUBG API

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

53 Commits

Folders and files

Repository files navigation

PUBG TypeScript API Wrapper

A comprehensive TypeScript wrapper for the PUBG API with full type safety, rate limiting, error handling, and caching.

Features

  • 🔒 Full TypeScript support with comprehensive type definitions
  • 🚦 Built-in rate limiting (10 requests per minute by default)
  • 🛡️ Comprehensive error handling with custom error types
  • 🔄 Automatic retries for failed requests
  • 💾 Client-local response caching with TTL and size limits
  • 📡 All PUBG API endpoints supported
  • 🎯 Easy-to-use service-based architecture
  • 🐛 Debug logging with multiple namespaces
  • ⚡ Performance monitoring with timing utilities
  • ❤️ Synchronous Client Health derived from real request outcomes
  • 📦 Local-only Asset Catalog with generated image URLs

Installation

npm install @j03fr0st/pubg-ts

Upgrading from v1? See MIGRATION.md for the breaking interface changes.

Quick Start

import { PubgClient } from '@j03fr0st/pubg-ts';

const client = new PubgClient({
  apiKey: 'your-api-key',
  shard: 'pc-na'
});

// Get player by name
const player = await client.players.getPlayerByName('playerName');

// Get match details
const match = await client.matches.getMatch('match-id');

// Get current season
const season = await client.seasons.getCurrentSeason();

API Reference

Players

// Get players by name
const players = await client.players.getPlayers({
  playerNames: ['player1', 'player2']
});

// Get player by ID
const player = await client.players.getPlayerById('player-id');

// Get player season stats
const stats = await client.players.getPlayerSeasonStats({
  playerId: 'player-id',
  seasonId: 'season-id'
});

Matches

// Get match details
const match = await client.matches.getMatch('match-id');

// Get matches with filters
const matches = await client.matches.getMatches({
  filter: {
    createdAt: {
      start: '2023-01-01T00:00:00Z',
      end: '2023-01-31T23:59:59Z'
    }
  }
});

Seasons

// Get all seasons
const seasons = await client.seasons.getSeasons();

// Get current season
const currentSeason = await client.seasons.getCurrentSeason();

Leaderboards

// Get leaderboard
const leaderboard = await client.leaderboards.getLeaderboard({
  seasonId: 'season-id',
  gameMode: 'squad'
});

Telemetry

// Get telemetry data from a match
const telemetry = await client.matches.getTelemetry(matchId);

Assets

AssetCatalog always reads bundled local data synchronously. assetBaseUrl only controls the image URLs generated by the catalog.

import { AssetCatalog, ItemId, VehicleId } from '@j03fr0st/pubg-ts';

// Every client owns a local catalog.
const itemId: ItemId = 'Item_Weapon_AK47_C';
const itemName = client.assets.getItemName(itemId); // "AKM"
const itemInfo = client.assets.getItemInfo(itemId);

// Enhanced search and filtering
const weapons = client.assets.getItemsByCategory('weapon');
const searchResults = client.assets.searchItems('AK');

// Vehicle information with type safety
const vehicleId: VehicleId = 'BP_Motorbike_04_C';
const vehicleName = client.assets.getVehicleName(vehicleId);
const vehicleInfo = client.assets.getVehicleInfo(vehicleId);

// Map data with comprehensive coverage
const allMaps = client.assets.getAllMaps();
const mapName = client.assets.getMapName('Baltic_Main');

// Season data by platform; Season Activity is read from the bundled dates at call time
const pcSeasons = client.assets.getSeasonsByPlatform('PC');
const activeSeason = client.assets.getActiveSeason('PC');

// Survival titles with rating ranges
const title = client.assets.getSurvivalTitle(1500);

// Asset statistics and insights
const stats = client.assets.getAssetStats();
console.log(`Total items: ${stats.totalItems}`);

// Standalone catalogs use the same local data and can customize generated image URLs.
const assets = new AssetCatalog({ assetBaseUrl: 'https://cdn.example.com/pubg' });
const weaponIconUrl = assets.getWeaponAssetUrl('Item_Weapon_AK47_C', 'icon');

Advanced Features

Caching

Each client caches eligible API responses locally:

const health = client.getHealth();
console.log(
  `Cache: ${health.responseCache.size}/${health.responseCache.maxSize} entries`
);

// Clear cache manually
client.clearResponseCache();

Debug Logging

Enable debug logging by setting the DEBUG environment variable:

# Enable all debug logs
DEBUG=pubg-ts:* node your-app.js

# Enable specific component logs
DEBUG=pubg-ts:http,pubg-ts:cache node your-app.js

Available debug namespaces:

  • pubg-ts:http - HTTP requests, timing, and retries
  • pubg-ts:cache - Cache hits, misses, and operations
  • pubg-ts:client - Client initialization and configuration

Rate Limiting

Inspect the last-known rate-limit state through Client Health:

const health = client.getHealth();
console.log(`Remaining requests: ${health.rateLimit.remaining}`);
console.log(`Reset time: ${health.rateLimit.resetAt ?? 'not observed'}`);

Error Handling

import { 
  PubgApiError, 
  PubgRateLimitError, 
  PubgAuthenticationError 
} from '@j03fr0st/pubg-ts';

try {
  const player = await client.players.getPlayerByName('nonexistent');
} catch (error) {
  if (error instanceof PubgRateLimitError) {
    console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof PubgAuthenticationError) {
    console.log('Invalid API key');
  }
}

Configuration

const client = new PubgClient({
  apiKey: 'your-api-key',
  shard: 'pc-na',
  baseUrl: 'https://api.pubg.com', // optional
  assetBaseUrl: 'https://cdn.example.com/pubg', // optional, generated asset URLs only
  timeout: 10000, // optional, default 10s
  retryAttempts: 3, // optional, default 0 (no retries); only transient 5xx responses are retried
  retryDelay: 1000 // optional, default 1s, doubled on each retry
});

Examples

Check out the examples directory for comprehensive usage examples:

Development

Code Formatting

This project uses Biome for fast, reliable linting and formatting:

# Format all files
npm run format

# Lint code
npm run lint

# Fix linting issues
npm run lint:fix

# Check and fix both formatting and linting
npm run check:fix

Asset Data

The checked-in JSON under src/assets/ is the Asset Catalog's only source of truth; building does not fetch or synchronize remote asset data. The identifier types under src/types/assets/ are generated from that JSON — after editing any bundled JSON, run:

npm run generate:asset-types
npm run check:asset-types # verify generated types without writing files (also runs in CI)

Testing

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

Pre-commit Hooks

This project uses Lefthook for pre-commit validation:

  • Automatic code formatting with Biome
  • Linting and type checking
  • Running tests for changed files

The hooks run automatically on git commit. To bypass (not recommended):

git commit --no-verify

Editor Setup

The project includes:

  • EditorConfig (.editorconfig) for consistent formatting across editors
  • VS Code settings (.vscode/) with recommended extensions and settings
  • Biome integration for automatic formatting on save

Recommended VS Code extensions:

  • EditorConfig for VS Code
  • Biome

Code Style

  • Indentation: 2 spaces
  • Quotes: Single quotes for strings
  • Line endings: LF (Unix)
  • Line length: 100 characters
  • Trailing commas: ES5 style
  • Import organization: Automatic sorting and grouping

Contributing

Please read CONTRIBUTING.md for details on our development process and how to submit pull requests.

Security

Please see SECURITY.md for information about reporting security vulnerabilities.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Open Source

This is an open source project and anyone is free to:

  • Use this software for any purpose
  • Modify and distribute the software
  • Include it in other projects (commercial or non-commercial)
  • Contribute improvements back to the project

The MIT License is one of the most permissive open source licenses, placing minimal restrictions on reuse.

About

A typescript wrapper for the PUBG API

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages