algolia-sdk-patterns
Apply production-ready algoliasearch v5 patterns: singleton client, typed search, error handling, and batch operations. Use when implementing Algolia integrations, refactoring SDK usage, or establishing team coding standards. Trigger: "algolia SDK patterns", "algolia best practices", "algolia code patterns", "idiomatic algolia".
What this skill does
# Algolia SDK Patterns
## Overview
Production-ready patterns for `algoliasearch` v5. Key architectural change from v4: all methods live on the client directly — no more `client.initIndex()`. Index name is passed as a parameter to every call.
## Prerequisites
- `algoliasearch` v5+ installed
- Completed `algolia-install-auth` setup
- TypeScript project (patterns work in JS too, you just lose type safety)
## Instructions
### Pattern 1: Typed Singleton Client
```typescript
// src/algolia/client.ts
import { algoliasearch, type Algoliasearch } from 'algoliasearch';
let _client: Algoliasearch | null = null;
export function getClient(): Algoliasearch {
if (!_client) {
const appId = process.env.ALGOLIA_APP_ID;
const apiKey = process.env.ALGOLIA_ADMIN_KEY;
if (!appId || !apiKey) {
throw new Error(
'ALGOLIA_APP_ID and ALGOLIA_ADMIN_KEY must be set. '
+ 'Get them from dashboard.algolia.com > Settings > API Keys'
);
}
_client = algoliasearch(appId, apiKey);
}
return _client;
}
// For testing: reset singleton
export function resetClient(): void {
_client = null;
}
```
### Pattern 2: Typed Search Results
```typescript
// src/algolia/types.ts
// Define your record shape — extends Algolia's Hit type
interface Product {
objectID: string;
name: string;
category: string;
price: number;
description: string;
image_url: string;
}
// src/algolia/search.ts
import { getClient } from './client';
export async function searchProducts(
query: string,
options?: {
filters?: string;
facetFilters?: string[][];
hitsPerPage?: number;
page?: number;
}
) {
const client = getClient();
const { hits, nbHits, nbPages, page } = await client.searchSingleIndex<Product>({
indexName: 'products',
searchParams: {
query,
filters: options?.filters,
facetFilters: options?.facetFilters,
hitsPerPage: options?.hitsPerPage ?? 20,
page: options?.page ?? 0,
attributesToRetrieve: ['name', 'category', 'price', 'image_url'],
attributesToHighlight: ['name', 'description'],
},
});
return { hits, totalHits: nbHits, totalPages: nbPages, currentPage: page };
}
// Usage: const { hits } = await searchProducts('laptop', { filters: 'price < 1000' });
```
### Pattern 3: Error Handling with Algolia Error Types
```typescript
// src/algolia/errors.ts
import { ApiError } from 'algoliasearch';
export async function safeAlgoliaCall<T>(
operation: string,
fn: () => Promise<T>
): Promise<{ data: T | null; error: string | null }> {
try {
const data = await fn();
return { data, error: null };
} catch (err) {
if (err instanceof ApiError) {
// ApiError has status and message from Algolia API
const msg = `Algolia ${operation} failed [${err.status}]: ${err.message}`;
console.error(msg);
// Specific handling for common codes
if (err.status === 429) {
console.warn('Rate limited — reduce request frequency or contact Algolia');
} else if (err.status === 404) {
console.warn('Index or object not found — verify index name');
}
return { data: null, error: msg };
}
// Non-Algolia error (network, etc.)
const msg = err instanceof Error ? err.message : 'Unknown error';
console.error(`${operation} error: ${msg}`);
return { data: null, error: msg };
}
}
// Usage:
// const { data, error } = await safeAlgoliaCall('search', () =>
// client.searchSingleIndex({ indexName: 'products', searchParams: { query: 'foo' } })
// );
```
### Pattern 4: Batch Operations
```typescript
// src/algolia/batch.ts
import { getClient } from './client';
// saveObjects handles batching internally — send up to 1000 objects per call
export async function bulkIndex(indexName: string, records: Record<string, any>[]) {
const client = getClient();
const BATCH_SIZE = 1000;
for (let i = 0; i < records.length; i += BATCH_SIZE) {
const batch = records.slice(i, i + BATCH_SIZE);
const { taskID } = await client.saveObjects({
indexName,
objects: batch,
});
await client.waitForTask({ indexName, taskID });
console.log(`Indexed ${Math.min(i + BATCH_SIZE, records.length)}/${records.length}`);
}
}
// Partial update — only send changed fields
export async function updateFields(
indexName: string,
objectID: string,
fields: Record<string, any>
) {
const client = getClient();
return client.partialUpdateObject({
indexName,
objectID,
attributesToUpdate: fields,
});
}
```
### Pattern 5: Multi-Tenant Client Factory
```typescript
// src/algolia/multi-tenant.ts
import { algoliasearch, type Algoliasearch } from 'algoliasearch';
const tenantClients = new Map<string, Algoliasearch>();
export function getClientForTenant(tenantId: string): Algoliasearch {
if (!tenantClients.has(tenantId)) {
// Each tenant might have their own Algolia app, or use index prefixes
const appId = process.env[`ALGOLIA_APP_ID_${tenantId.toUpperCase()}`]
|| process.env.ALGOLIA_APP_ID!;
const apiKey = process.env[`ALGOLIA_ADMIN_KEY_${tenantId.toUpperCase()}`]
|| process.env.ALGOLIA_ADMIN_KEY!;
tenantClients.set(tenantId, algoliasearch(appId, apiKey));
}
return tenantClients.get(tenantId)!;
}
// Or use a single app with index prefixing
export function tenantIndex(tenantId: string, base: string): string {
return `${tenantId}_${base}`; // "acme_products"
}
```
## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| `safeAlgoliaCall` wrapper | All API calls | Prevents uncaught exceptions, structured error info |
| `ApiError` check | Distinguishing API vs network errors | Targeted retry/recovery logic |
| `waitForTask` | After every write operation | Ensures reads see latest data |
| Batch chunking | Large datasets | Avoids record-too-big and timeout errors |
## Resources
- [algoliasearch v5 Methods](https://www.algolia.com/doc/libraries/javascript/v5/methods/search/)
- v4 to v5 Migration Guide
- API Error Codes
## Next Steps
Apply patterns in `algolia-core-workflow-a` for search implementation.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.