PlayableLabs Docs
Nhà Phát Triển

SDK và Ví Dụ

Ví dụ API client bằng TypeScript và JavaScript, các pattern thường dùng và kế hoạch SDK tương lai

Tổng Quan

PlayableLabs chưa có gói SDK chính thức. Tuy nhiên, REST API dễ sử dụng với bất kỳ HTTP client nào. Trang này cung cấp các pattern code sẵn dùng cho các thao tác thường gặp.

TypeScript API Client

Client tối giản với type an toàn cho dự án TypeScript:

const API_BASE = 'https://api.playablelabs.ai/api'

interface RequestOptions {
  method?: string
  body?: Record<string, unknown>
  params?: Record<string, string>
}

async function apiClient<T>(
  endpoint: string,
  token: string,
  options: RequestOptions = {}
): Promise<T> {
  const { method = 'GET', body, params } = options

  const url = new URL(`${API_BASE}${endpoint}`)
  if (params) {
    Object.entries(params).forEach(([key, value]) =>
      url.searchParams.set(key, value)
    )
  }

  const response = await fetch(url.toString(), {
    method,
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: body ? JSON.stringify(body) : undefined,
  })

  if (!response.ok) {
    const error = await response.json()
    throw new Error(error.message || `API error: ${response.status}`)
  }

  return response.json()
}

Các Pattern Thường Dùng

Danh Sách Game Có Phân Trang

interface PaginatedResponse<T> {
  data: T[]
  meta: { page: number; limit: number; total: number; totalPages: number }
}

interface Game {
  id: string
  name: string
  createdAt: string
}

const games = await apiClient<PaginatedResponse<Game>>(
  '/games',
  'YOUR_TOKEN',
  { params: { page: '1', limit: '20' } }
)

console.log(`Tìm thấy ${games.meta.total} game`)

Tải Tài Nguyên Lên

Tải tài nguyên sử dụng pre-signed URL. Quy trình gồm hai bước:

// Bước 1: Lấy pre-signed upload URL
const { uploadUrl, assetId } = await apiClient<{
  uploadUrl: string
  assetId: string
}>('/storage/urls', 'YOUR_TOKEN', {
  method: 'POST',
  body: {
    fileName: 'hero-sprite.png',
    contentType: 'image/png',
    organizationId: 'YOUR_ORG_ID',
  },
})

// Bước 2: Tải file trực tiếp lên storage
await fetch(uploadUrl, {
  method: 'PUT',
  headers: { 'Content-Type': 'image/png' },
  body: fileBuffer,
})

Kích Hoạt Xuất

const exportResult = await apiClient('/export', 'YOUR_TOKEN', {
  method: 'POST',
  body: {
    variantId: 'VARIANT_ID',
    network: 'unity',
  },
})

Pattern Xử Lý Lỗi

try {
  const games = await apiClient('/games', 'YOUR_TOKEN')
  console.log(games)
} catch (error: unknown) {
  if (error instanceof Error) {
    if (error.message.includes('401')) {
      console.error('Token không hợp lệ hoặc đã hết hạn')
    } else if (error.message.includes('429')) {
      console.error('Bị giới hạn tần suất -- thử lại sau')
    } else {
      console.error('Lỗi API:', error.message)
    }
  }
}

Tham Chiếu Nhanh cURL

# Danh sách game
curl -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.playablelabs.ai/api/games?page=1&limit=10"

# Lấy một game
curl -H "Authorization: Bearer YOUR_TOKEN" \
  https://api.playablelabs.ai/api/games/GAME_ID

# Danh sách tài nguyên
curl -H "Authorization: Bearer YOUR_TOKEN" \
  "https://api.playablelabs.ai/api/assets?organizationId=YOUR_ORG_ID"

# Kích hoạt xuất
curl -X POST \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"variantId":"VARIANT_ID","network":"unity"}' \
  https://api.playablelabs.ai/api/export

Kế Hoạch SDK Tương Lai

Các gói SDK chính thức dự kiến cho:

  • npm (@playablelabs/sdk) -- TypeScript/JavaScript client với type đầy đủ
  • Python (playablelabs) -- Cho data pipeline và quy trình tự động hóa

Tính năng SDK dự kiến:

  • Tự động phân trang
  • Logic thử lại với exponential backoff
  • Hỗ trợ làm mới và xoay vòng token
  • Interface request và response có type

Cho đến khi SDK chính thức có sẵn, sử dụng các pattern trên trang này làm điểm khởi đầu.

Bước Tiếp Theo

On this page