LO

lokalise-sdk-patterns

Provides standard patterns for Lokalise SDK including client singletons, pagination, and error handling.

Install

mkdir -p .claude/skills/lokalise-sdk-patterns && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/4689" && unzip -o skill.zip -d .claude/skills/lokalise-sdk-patterns && rm skill.zip

Installs to .claude/skills/lokalise-sdk-patterns

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Apply production-ready Lokalise SDK patterns for TypeScript and Node.js.
72 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Create client singletons for centralized configuration
  • Wrap API calls with structured retryable error handling
  • Batch key creation and deletion operations
  • Monitor file upload processes with progress callbacks

How it works

The pattern uses a singleton client to manage authentication and provides utility functions for pagination, batching, and retrying requests to respect API rate limits.

Inputs & outputs

You give it
Lokalise API token and project parameters
You get back
Paginated API results or batch operation status reports

When to use lokalise-sdk-patterns

  • Create a client singleton
  • Implement cursor-based pagination
  • Standardize error handling
  • Refactor SDK usage

About this skill

Lokalise SDK Patterns

Overview

Production-grade patterns for @lokalise/node-api: client singleton, cursor pagination, typed error handling, batch operations, upload monitoring, and retry with rate limiting.

Prerequisites

  • @lokalise/node-api v12+ installed
  • TypeScript 5+ with strict mode

Instructions

  1. Create a client singleton to centralize configuration and support branch-based project IDs.
// src/lib/lokalise-client.ts
import { LokaliseApi } from "@lokalise/node-api";

let instance: LokaliseApi | null = null;

export function getClient(apiKey?: string): LokaliseApi {
  if (instance) return instance;
  const key = apiKey ?? process.env.LOKALISE_API_TOKEN;
  if (!key) throw new Error("Set LOKALISE_API_TOKEN or pass apiKey");
  instance = new LokaliseApi({ apiKey: key, enableCompression: true });
  return instance;
}

export function resetClient(): void { instance = null; }

/** Lokalise branch syntax: "projectId:branchName" */
export function projectId(id: string, branch?: string): string {
  return branch ? `${id}:${branch}` : id;
}
  1. Build a cursor-based pagination helper that works with any paginated endpoint.
// src/lib/paginate.ts
interface PaginatedResult<T> {
  items: T[];
  hasNextCursor(): boolean;
  nextCursor(): string;
}

type Fetcher<T> = (params: Record<string, unknown>) => Promise<PaginatedResult<T>>;

/** Async generator yielding all items across pages with rate-limit spacing. */
export async function* paginate<T>(
  fetcher: Fetcher<T>,
  baseParams: Record<string, unknown>,
  pageSize = 500
): AsyncGenerator<T, void, undefined> {
  let cursor: string | undefined;
  let n = 0;
  do {
    const params = { ...baseParams, limit: pageSize, ...(cursor ? { cursor } : {}) };
    if (n++ > 0) await new Promise((r) => setTimeout(r, 170)); // 6 req/sec
    const page = await fetcher(params);
    for (const item of page.items) yield item;
    cursor = page.hasNextCursor() ? page.nextCursor() : undefined;
  } while (cursor);
}

/** Collect all pages into an array (use only when dataset fits in memory). */
export async function paginateAll<T>(fetcher: Fetcher<T>, params: Record<string, unknown>): Promise<T[]> {
  const out: T[] = [];
  for await (const item of paginate(fetcher, params)) out.push(item);
  return out;
}

Usage:

const allKeys = await paginateAll(
  (p) => client.keys().list(p),
  { project_id: "123456.abcdef", include_translations: 1 }
);
  1. Wrap API calls with structured error handling that classifies retryable errors.
// src/lib/lokalise-api.ts
export class LokaliseError extends Error {
  constructor(
    message: string,
    public readonly statusCode: number,
    public readonly isRetryable: boolean
  ) {
    super(message);
    this.name = "LokaliseError";
  }
}

export async function apiCall<T>(fn: () => Promise<T>): Promise<T> {
  try {
    return await fn();
  } catch (err: unknown) {
    if (err && typeof err === "object" && "code" in err) {
      const e = err as { code: number; message: string };
      throw new LokaliseError(e.message, e.code, e.code === 429 || e.code >= 500);
    }
    throw err;
  }
}

// Usage
try {
  const keys = await apiCall(() => client.keys().list({ project_id: pid, limit: 500 }));
} catch (err) {
  if (err instanceof LokaliseError && err.isRetryable) {
    console.log("Transient failure, safe to retry");
  }
}
  1. Batch key operations that chunk requests to respect the 500-key-per-request limit.
// src/lib/batch.ts
function chunk<T>(arr: T[], size: number): T[][] {
  const out: T[][] = [];
  for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
  return out;
}

/** Create keys in batches of 500 with rate-limit spacing. */
export async function batchCreateKeys(
  client: LokaliseApi, projectId: string,
  keys: Array<{ key_name: { web: string }; platforms: string[]; tags?: string[];
    translations?: Array<{ language_iso: string; translation: string }> }>
): Promise<{ created: number; errors: Error[] }> {
  const batches = chunk(keys, 500);
  let created = 0;
  const errors: Error[] = [];
  for (let i = 0; i < batches.length; i++) {
    try {
      const r = await client.keys().create({ project_id: projectId, keys: batches[i] });
      created += r.items.length;
    } catch (err) { errors.push(err as Error); }
    if (i < batches.length - 1) await new Promise((r) => setTimeout(r, 500));
  }
  return { created, errors };
}

/** Delete keys in batches of 500. */
export async function batchDeleteKeys(
  client: LokaliseApi, projectId: string, keyIds: number[]
): Promise<number> {
  const batches = chunk(keyIds, 500);
  let deleted = 0;
  for (let i = 0; i < batches.length; i++) {
    const r = await client.keys().bulk_delete(batches[i], { project_id: projectId });
    deleted += r.keys_removed;
    if (i < batches.length - 1) await new Promise((r) => setTimeout(r, 500));
  }
  return deleted;
}
  1. Upload files with async process monitoring and progress callbacks.
// src/lib/upload.ts
import { readFileSync } from "node:fs";

export async function uploadWithProgress(
  client: LokaliseApi, projectId: string,
  opts: { filePath: string; langIso: string; tags?: string[];
    replaceModified?: boolean; cleanupMode?: boolean },
  onProgress?: (status: string, elapsedMs: number) => void
): Promise<{ processId: string; status: string; durationMs: number }> {
  const data = readFileSync(opts.filePath).toString("base64");
  const start = Date.now();

  const proc = await client.files().upload(projectId, {
    data,
    filename: opts.filePath.split("/").pop()!,
    lang_iso: opts.langIso,
    replace_modified: opts.replaceModified ?? true,
    cleanup_mode: opts.cleanupMode ?? false,
    detect_icu_plurals: true,
    tags: opts.tags,
  });
  onProgress?.("queued", Date.now() - start);

  // Poll process status until terminal state
  const maxWait = 120_000; // 2 minutes
  let last = proc.status;
  while (Date.now() - start < maxWait) {
    await new Promise((r) => setTimeout(r, 1500));
    const check = await client.queuedProcesses().get(proc.process_id, { project_id: projectId });
    if (check.status !== last) { last = check.status; onProgress?.(last, Date.now() - start); }
    if (check.status === "finished") return { processId: proc.process_id, status: "finished", durationMs: Date.now() - start };
    if (check.status === "cancelled" || check.status === "failed") throw new Error(`Upload ${check.status}: ${JSON.stringify(check.details)}`);
  }
  throw new Error(`Upload timed out after ${maxWait}ms`);
}

Usage:

await uploadWithProgress(client, "123456.abcdef", {
  filePath: "./src/locales/en.json",
  langIso: "en",
  tags: ["ci"],
  replaceModified: true,
}, (status, ms) => console.log(`[${(ms / 1000).toFixed(1)}s] ${status}`));
  1. Add a retry decorator with exponential backoff and a rate limiter for sequential calls.
// src/lib/retry.ts
/** Retry on 429 and 5xx with exponential backoff + jitter. */
export async function withRetry<T>(
  fn: () => Promise<T>,
  opts: { maxRetries?: number; baseDelayMs?: number; maxDelayMs?: number;
    onRetry?: (attempt: number, err: Error, delayMs: number) => void } = {}
): Promise<T> {
  const { maxRetries = 3, baseDelayMs = 1000, maxDelayMs = 10_000, onRetry } = opts;
  let lastErr: Error | undefined;
  for (let i = 0; i <= maxRetries; i++) {
    try { return await fn(); }
    catch (err: unknown) {
      lastErr = err as Error;
      const code = (err as { code?: number })?.code;
      if (!(code === 429 || (code && code >= 500)) || i === maxRetries) throw err;
      const delay = Math.min(baseDelayMs * 2 ** i + Math.random() * 200, maxDelayMs);
      onRetry?.(i + 1, lastErr, delay);
      await new Promise((r) => setTimeout(r, delay));
    }
  }
  throw lastErr;
}

/** Enforce minimum spacing between calls (default: 170ms = 6 req/sec). */
export function rateLimited<A extends unknown[], R>(
  fn: (...args: A) => Promise<R>, minMs = 170
): (...args: A) => Promise<R> {
  let last = 0;
  return async (...args) => {
    const wait = minMs - (Date.now() - last);
    if (wait > 0) await new Promise((r) => setTimeout(r, wait));
    last = Date.now();
    return fn(...args);
  };
}

Usage:

// Single call with retry
const keys = await withRetry(
  () => client.keys().list({ project_id: pid, limit: 500 }),
  { onRetry: (n, e, ms) => console.warn(`Retry ${n}: ${e.message} (${ms}ms)`) }
);

// Rate-limited sequential calls
const listKeys = rateLimited((p: Record<string, unknown>) => client.keys().list(p));
const p1 = await listKeys({ project_id: pid, page: 1, limit: 100 });
const p2 = await listKeys({ project_id: pid, page: 2, limit: 100 });

Output

  • Singleton client with compression and branch support
  • Async generator for memory-efficient cursor pagination
  • Type-safe error wrapper with isRetryable classification
  • Batch create/delete respecting 500-key API limit
  • File upload with process polling and progress callbacks
  • Retry with exponential backoff + rate limiter at 6 req/sec

Error Handling

PatternWhen to UseBehavior
apiCall()Every SDK callConverts to typed LokaliseError with isRetryable
withRetry()Rate limits or transient failuresExponential backoff, retries 429 and 5xx only
rateLimited()Sequential bulk callsEnforces 170ms minimum spacing
paginate()Fetching all keys/translationsBuilt-in 170ms delay between pages
batchCreateKeys()Creating > 500 keys500-key chunks with 500ms spacing
uploadWithProgress()File uploadsPolls process status with 2-minute timeout

Examples

Combining All Patterns

import { getClient, projectId } from "./lib/lokalise-client";
import { paginateAll } from "./lib/paginate";
import { withRetry } from "./lib/retry";
import { batchCreateKeys

---

*Content truncated.*

When not to use it

  • When performing single, non-repetitive API calls where overhead is unnecessary
  • When the dataset is small enough to fit in a single API response

Prerequisites

@lokalise/node-api v12+TypeScript 5+ with strict mode

Limitations

  • Batch operations are limited to 500 items per request
  • Pagination requires a 170ms minimum spacing between requests
  • Upload monitoring has a 2-minute timeout

How it compares

This approach standardizes error classification and request throttling, whereas manual implementation often lacks consistent retry logic and rate-limit handling.

Compared to similar skills

lokalise-sdk-patterns side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
lokalise-sdk-patterns (this skill)127dReviewIntermediate
telegram-mini-app626moReviewAdvanced
stripe-integration482moNo flagsAdvanced
nodejs-backend-patterns122moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

telegram-mini-app

davila7

Expert in building Telegram Mini Apps (TWA) - web apps that run inside Telegram with native-like experience. Covers the TON ecosystem, Telegram Web App API, payments, user authentication, and building viral mini apps that monetize. Use when: telegram mini app, TWA, telegram web app, TON app, mini app.

62163

stripe-integration

wshobson

Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.

48165

nodejs-backend-patterns

wshobson

Build production-ready Node.js backend services with Express/Fastify, implementing middleware patterns, error handling, authentication, database integration, and API design best practices. Use when creating Node.js servers, REST APIs, GraphQL backends, or microservices architectures.

1246

agent-dev-backend-api

ruvnet

Agent skill for dev-backend-api - invoke with $agent-dev-backend-api

318

shopify-apps

alinaqi

Shopify app development - Remix, Admin API, checkout extensions

19

ccxt-typescript

ccxt

CCXT cryptocurrency exchange library for TypeScript and JavaScript developers (Node.js and browser). Covers both REST API (standard) and WebSocket API (real-time). Helps install CCXT, connect to exchanges, fetch market data, place orders, stream live tickers/orderbooks, handle authentication, and manage errors. Use when working with crypto exchanges in TypeScript/JavaScript projects, trading bots, arbitrage systems, or portfolio management tools. Includes both REST and WebSocket examples.

15

Search skills

Search the agent skills registry