@plyaz/api ⚡ Core Plyaz API client enabling seamless Web3 interactions, authentication, and data access across apps and services. Built for scalability, reliability, and tokenized fan engagement experiences.
npm install @plyaz/api> ⚡ Smart, type-safe API client for the Plyaz ecosystem with zero-configuration intelligence



@plyaz/api is the unified API client for seamless backend communication across the Plyaz platform. Built on fetchff, it provides intelligent defaults, automatic optimizations, and full TypeScript support for Web3, authentication, and tokenized experiences.
---
The API client works intelligently out of the box:
| Feature | What It Does | Default Behavior | When to Override |
|---------|--------------|------------------|------------------|
| Request Deduplication | Prevents duplicate requests | 2-second window | Real-time data needs |
| Automatic Retry | Retries failed requests | 3 retries with exponential backoff | Critical operations |
| Response Caching | Caches successful responses | 10min cache, 2min stale | Static vs real-time data |
| Network Adaptation | Adjusts to connection quality | Automatic detection | Custom performance needs |
| Smart Headers | Sets appropriate headers | JSON content-type | File uploads, GraphQL |
| Timeout Handling | Prevents hanging requests | 30 seconds | Long-running operations |
All endpoints are pre-defined and fully typed. No configuration needed:
``typescript
const api = await createApiClient({ baseURL: 'https://api.example.com' });
// Pre-configured, fully typed methods ready to use!
const { data } = await api.getUsers();
const { data: campaign } = await api.getCampaign({ id: '123' });
`
---
`bash`
pnpm add @plyaz/api
Requirements:
- Node.js >= 22.4.0
- pnpm >= 8.0.0
---
`typescript`
const api = await createApiClient({ baseURL: 'https://api.example.com' });
const { data } = await api.getUsers();
`typescriptBearer ${await getToken()}
const api = await createApiClient({
baseURL: 'https://api.example.com',
headers: async () => ({
Authorization: `
})
});
`typescript`
const api = await createApiClient({
baseURL: 'https://api.example.com',
performanceStrategy: 'mobile',
networkAware: { enabled: true }
});
`typescript`
const api = await createApiClient({
baseURL: 'https://api.example.com',
unifiedStrategy: 'realtime',
revalidationStrategy: 'aggressive'
});
---
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 🔒 Type Safety | Auto | Full TypeScript support with intelligent type inference | Enabled | N/A - Always active |
| ⚡ Smart Defaults | Auto | Zero-config setup, works perfectly out of the box | Enabled | Override via config |
| 📋 Pre-Configured Endpoints | Auto | Typed endpoint methods ready to use | All endpoints | Override with endpoints |dedupeTime: number
| 🔁 Request Deduplication | Auto | Prevents duplicate requests within time window | 2-second window | |timeout: number
| ⏱️ Timeout Handling | Auto | Prevents hanging requests | 30 seconds | |cancellable: true
| 🚦 Request Cancellation | Manual | AbortController support | Available | |onRequest
| 🔗 Request Chaining | Manual | Chain multiple requests efficiently | Available | Standard usage |
| 🔌 Interceptors | Manual | Request/response/error interceptors | None | , onResponse, onError |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 🔄 Retry Logic | Auto | Exponential backoff for failed requests | 3 retries, 1s delay, 1.5x backoff | retry: { retries, delay, backoff } |standard
| 🎯 Retry Strategies | Manual | Customizable retry strategies (none, minimal, standard, etc.) | | retryStrategy: string |retryOn: number[]
| 🔍 Retry Conditions | Manual | Conditional retry based on status codes, errors | Standard HTTP errors | |
| ⚠️ Status Code Limits | Manual | Define retry behavior per status code | 408, 429, 500, 502, 503, 504 | Custom limits |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 💾 Response Caching | Auto | Multi-level caching (memory, session, persistent) | 10min cache, 2min stale | cacheTime, staleTime |standard
| 📦 Cache Strategies | Manual | 6 strategies (none, minimal, standard, moderate, aggressive, offline) | | cacheStrategy: string |buildCacheKey()
| 🔑 Cache Key Patterns | Manual | Custom cache key generation patterns | Standard pattern | |mutate()
| 🗑️ Cache Invalidation | Manual | Invalidation scenarios and utilities | Available | , deleteCache() |revalidationStrategy: string
| ♻️ Revalidation | Auto | 9 strategies (focus, reconnect, interval, etc.) | On focus/reconnect | |revalidate()
| 🔄 Manual Revalidation | Manual | Programmatic cache revalidation | Available | , revalidateAll() |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 🌐 Network Detection | Auto | Detects connection quality and adapts | Enabled | networkAware: { enabled } |standard
| 📊 Network Quality | Auto | Monitors network quality (excellent, good, slow, offline) | Automatic | Auto-detection |
| 🎯 Performance Strategies | Manual | Optimized presets (mobile, realtime, static, etc.) | | performanceStrategy: string |
| ⚙️ Network Config Manager | Auto | Manages network-optimized configurations | Enabled | Automatic management |
| 💻 Platform Detection | Auto | Detects platform (browser, Node.js, Electron, etc.) | Automatic | Auto-detection |
| 📱 Device Detection | Auto | Detects device type and capabilities | Automatic | Auto-detection |
| 🔍 Client Hints | Auto | Enhanced client hints for network optimization | Enabled | Automatic detection |
| ⚡ Adaptive Performance | Auto | Adapts behavior based on device/network | Enabled | Automatic adaptation |
| 📈 Performance Monitoring | Auto | Tracks request timing and performance metrics | Enabled | Automatic tracking |
| 💤 Data Saver Mode | Auto | Detects and respects data saver preferences | Enabled | Automatic detection |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 📝 Header Management | Auto | Smart header enrichment and presets | JSON content-type | headers: {} or headers: () => {} |enrichedHeaders: boolean
| ✨ Enriched Headers | Auto | Automatic header enrichment with platform/network data | Enabled | |headerPresets
| 🎨 Header Presets | Manual | Pre-configured header sets (json, multipart, etc.) | Available | |onRequest
| 🔐 Authentication | Manual | Token management and auth interceptors | None | interceptor |regionalConfig
| 🌍 Regional Compliance | Auto | GDPR, CCPA, APAC support | Enabled | |
| 🗺️ Regional Detection | Auto | Auto-detect user region for compliance | Enabled | Automatic detection |
| 🎯 Regional Presets | Manual | Region-specific configuration presets | Available | Regional presets |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 📊 Config Levels | Auto | 4-level hierarchy (global → client → request → temporary) | All levels active | Config hierarchy |
| 🔄 Config Merging | Auto | Smart deep merging of configuration objects | Enabled | Automatic merging |
| ⚙️ Merge Strategies | Manual | Custom merge strategies for config properties | Deep merge | Custom strategies |
| 🔀 Temporary Overrides | Manual | Temporary config overrides with auto-reset | Available | applyTemporaryOverride() |configOverride.strategy
| 📋 Override Tracking | Auto | Tracks all configuration overrides | Enabled | Automatic tracking |
| 🎯 Config Update Strategy | Manual | 3 strategies (merge, replace, temporary) | Merge | |configOverride.handlerStrategy
| 🎨 Handler Strategy | Manual | 4 strategies (merge, replace, prepend, append) | Merge | |configOverride.eventScopes
| 📍 Event Scopes Control | Manual | Control which scopes receive events | All scopes | |configOverride.clearOnComplete
| 🧹 Auto-Clear Overrides | Manual | Auto-clear temporary overrides after request | Disabled | |configOverride.priority
| ⚡ Priority Mode | Manual | Only highest priority handler runs | Disabled | |useApiConfigConflicts()
| 💾 Preserved Config | Auto | Preserves original config for restoration | Enabled | Automatic preservation |
| 🔍 Config Debugger | Manual | Detect configuration conflicts | Available | |checkConflicts()
| ⚠️ Conflict Detection | Manual | Detects conflicting configurations | Available | |
| 🌐 Global Config API | Manual | Set/get/update global configuration | Available | Global config methods |
| 📝 Config Validation | Auto | Validates configuration at runtime | Enabled | Automatic validation |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 🎛️ Master Tracking Switch | Manual | Enable/disable all tracking features | Enabled | tracking.enabled |tracking.operations
| 📊 Operation Tracking | Manual | Track operations for debugging (debugger queue) | Enabled | |tracking.events
| 📡 Event Emission Control | Manual | Control whether events are emitted/processed | Enabled | |tracking.queueStrategy
| ⚙️ Queue Strategy | Manual | 4 strategies (immediate, batch, throttle, debounce) | Batch | |tracking.eventStrategy
| 📤 Event Strategy | Manual | Event processing (immediate, queued) | Immediate | |tracking.performanceMode
| ⚡ Performance Mode | Manual | 3 modes (full, minimal, off) | Full | |tracking.historySize
| 📜 History Size Limit | Manual | Max operations to keep in history | 1000 | |tracking.maxConflicts
| ⚠️ Max Conflicts Tracking | Manual | Max conflicts to track | 100 | |tracking.skipHistory
| 🚫 Skip History | Manual | Skip adding entries to history for this request | Disabled | |tracking.telemetry
| 📈 Telemetry Collection | Manual | Analytics/monitoring data collection | Disabled | |
| 🎯 Context-Aware Tracking | Auto | Different defaults for test vs production | Auto-detected | Environment-based |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 📊 Event System | Auto | 80+ events across 8 namespaces | Enabled | on(), off(), emit() |handlerStrategy
| 🎯 Event Namespaces | Auto | 8 namespaces (headers, network, errors, debug, config, perf, client, cache) | All active | Namespace filtering |
| 📍 Event Scopes | Auto | 4 scopes (GLOBAL → CONFIG → CLIENT → REQUEST) | All scopes | Scope-based handlers |
| 🔄 Handler Strategies | Manual | 4 strategies (merge, replace, prepend, append) | Merge | config |useApiMonitor()
| ⚡ Event Priorities | Auto | Priority-based event execution | By scope priority | Automatic prioritization |
| ⚙️ Queue System | Auto | Priority-based async operation processing | Enabled | Automatic batching |
| 📦 Batch Processing | Auto | Batches events for efficient processing | 10ms window | Batch config |
| 🔔 Network Events | Auto | Network state change events | Enabled | Event subscriptions |
| 📦 PubSub System | Manual | Real-time subscriptions and updates | Available | Event subscriptions |
| 🎣 React Hooks | Manual | 4 monitoring hooks (monitor, debug, config, network) | Available | , etc. |getEventStats()
| 📈 Event Statistics | Manual | Get stats on event emissions and handlers | Available | |once()
| 🎯 Scoped Handlers | Manual | Register handlers at specific scopes | Available | Scope parameter |
| ⏱️ Once Handlers | Manual | Handlers that execute only once | Available | method |off()
| 🚫 Handler Removal | Manual | Unregister event handlers | Available | method |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 🐛 Debug Tools | Manual | Built-in debugging and analysis tools | Available | getDebugInfo() |generateReport()
| 📋 Debug Reporting | Manual | Generate comprehensive debug reports | Available | |
| 📊 Operation Tracking | Auto | Tracks all API operations for debugging | Enabled | Automatic tracking |
| 📜 History Tracking | Auto | Maintains request/response history (LRU) | Enabled | Automatic tracking |
| 🔍 Issue Analysis | Manual | Analyzes issues and provides recommendations | Available | Debug factories |
| 📊 Performance Analysis | Manual | Analyzes performance bottlenecks | Available | Performance factory |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 🎯 Unified Strategies | Manual | Combined strategy presets (realtime, mobile, etc.) | Available | unifiedStrategy: string |
| 🔄 Polling Strategies | Manual | Progressive, conditional, visibility-aware polling | Available | Polling config |
| ♻️ Revalidation Strategies | Manual | 9 revalidation patterns | On focus/reconnect | Strategy config |
| ⏰ Visibility-Aware | Auto | Pauses operations when tab inactive | Enabled | Automatic behavior |
| 📈 Progressive Polling | Manual | Gradually increasing poll intervals | Available | Progressive config |
| 🎯 Conditional Polling | Manual | Poll based on conditions | Available | Conditional config |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| ❌ Error Handling | Auto | Standardized error handling with @plyaz/errors | 18 error types | strategy: 'softFail' \| 'reject' |softFail
| 🎯 Error Strategies | Manual | softFail, reject, silent, defaultResponse | | strategy config |
| 🔔 Error Events | Auto | Error event handlers (global, instance, once) | Enabled | Error event handlers |
| 📊 Error Categories | Auto | Categorized errors (network, validation, auth, etc.) | Automatic | Built-in categories |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 🚀 Next.js Middleware | Manual | Next.js-specific integrations | Available | Framework middleware |
| ⚡ Express Middleware | Manual | Express server-side integration | Available | Framework middleware |
| 🎯 NestJS Integration | Manual | NestJS decorators and providers | Available | Framework middleware |
| 💻 SSR Support | Auto | Server-side rendering safe operations | Enabled | SSR-safe configs |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 🆔 ID Generation | Auto | Request ID, Correlation ID generation | Enabled | Automatic generation |
| ⏱️ Time Utilities | Manual | Time formatting, duration, delays | Available | Utility functions |
| 🔢 Math Utilities | Manual | Percentage, clamping, averaging | Available | Utility functions |
| 📝 String Utilities | Manual | String manipulation helpers | Available | Utility functions |
| 📦 Object Utilities | Manual | Deep merge, clone, access | Available | Utility functions |
| 🔍 Type Guards | Manual | Runtime type checking | Available | Utility functions |
| ✅ Validation | Manual | Data validation utilities | Available | Utility functions |
| ⏰ Interval Manager | Manual | Manage polling intervals | Available | Utility functions |
| 🎨 JSON Utilities | Manual | Safe JSON parsing/stringifying | Available | Utility functions |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 📋 Endpoint Builders | Manual | Fluent API for building endpoint configurations | Available | Endpoint builder pattern |
| 🏗️ Endpoint Utilities | Manual | Helper utilities for endpoint management | Available | Utility functions |
| 🎯 Services Layer | Manual | Service functions with smart defaults per HTTP method | Available | ServiceOptions |
| 🔧 Campaign Services | Manual | Complete CRUD operations for campaigns | Available | Service layer |
| 🎣 React Query Hooks | Manual | Pre-built hooks (useCampaigns, useCreateCampaign, etc.) | Available | Hook factories |
| 📦 Endpoint Registry | Auto | Maintains registry of all configured endpoints | Enabled | Automatic registration |
| 🔍 Endpoint Validation | Auto | Validates endpoint configurations | Enabled | Automatic validation |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 📝 Request Preparation | Auto | Prepares requests with proper formatting | Enabled | Automatic preparation |
| 🚫 Abort Management | Manual | Manage request cancellation via AbortController | Available | Abort utilities |
| 🔍 Request Routing | Auto | Routes requests through proper pipeline | Enabled | Automatic routing |
| 📊 Request Utils | Manual | Request preparation and management utilities | Available | Utility functions |
| 🆔 Request ID Tracking | Auto | Automatic request ID generation and tracking | Enabled | Automatic generation |
| 🔗 Correlation ID | Auto | Correlation ID for distributed tracing | Enabled | Automatic generation |
| Feature | Type | Description | Default | Configuration |
|---------|------|-------------|---------|---------------|
| 🔍 Request Fingerprinting | Auto | Generates unique fingerprints for requests | Enabled | Automatic generation |
| 🔐 Header Sanitization | Auto | Removes sensitive headers from logs | Enabled | Automatic sanitization |
| 🔍 Authentication Detection | Auto | Detects auth type from headers | Enabled | Automatic detection |
| 📦 Multiple Clients | Manual | Create and manage multiple client instances | Available | Standard usage |
| 🎯 Extended API Client | Manual | ApiClientWithEvents with enhanced features | Available | Create extended client |
| 🔄 Client Factory Pattern | Manual | Factory pattern for creating specialized clients | Available | Factory functions |
| 🎨 Color Utilities | Manual | Console color utilities for logging | Available | Color helpers |
| 🌐 Environment Detection | Auto | Detects runtime environment (browser/Node/Deno/Bun) | Enabled | Automatic detection |
| 📱 Push Notification Support | Auto | Detects push notification capabilities | Enabled | Automatic detection |
---
`typescript
interface ServiceOptions {
/**
* Optional API client instance override
* Use this when you need a different client configuration
* The client should have all endpoints from EndpointsList
*/
apiClient?: ApiClientWithEvents
/**
* Optional API configuration updates
* By default applied with { strategy: 'temporary' } mode (affects only this request)
* Can be overridden via updateConfigOptions
*/
apiConfig?: Partial
/**
* Optional update config options
* Controls how apiConfig is applied to the client
*
* Defaults to: { strategy: 'temporary' }
* - 'temporary': Only affects this request (highest priority)
* - 'merge': Merges with client config (persists)
* - 'replace': Replaces client config (persists)
*/
updateConfigOptions?: UpdateConfigOptions;
}
/**
* Config update options
*/
interface UpdateConfigOptions {
strategy?: ConfigUpdateStrategy;
priority?: number;
namespace?: string;
scope?: string;
preserveFields?: (keyof ApiConfig)[];
}
`
| Strategy | Cache | Retry | Use Case | Default For |
|----------|-------|-------|----------|-------------|
| realtime | None | Low | Live data, mutations | POST/PUT/DELETE |
| interactive | 2min stale, 10min cache | Medium | User-facing lists | GET (lists) |
| background | 10min stale, 30min cache | Medium | Background refreshes | GET (single items) |
| mobile | 5min stale, 15min cache | High | Mobile networks | - |
| static | 1hr stale, 24hr cache | Low | Rarely-changing data | - |
`typescript
// Pattern 1: Mobile-optimized
const serviceOptions: ServiceOptions = {
apiConfig: {
unifiedStrategy: 'mobile',
networkAware: { enabled: true, adaptConfig: true },
retry: { retries: 5, backoff: 2 }
}
};
// Pattern 2: Real-time dashboard
const serviceOptions: ServiceOptions = {
apiConfig: {
unifiedStrategy: 'realtime',
revalidationStrategy: 'aggressive',
cacheStrategy: 'none'
}
};
// Pattern 3: Static content
const serviceOptions: ServiceOptions = {
apiConfig: {
unifiedStrategy: 'static',
cacheStrategy: 'aggressive',
timeout: 10000
}
};
// Pattern 4: Custom fine-tuned
const serviceOptions: ServiceOptions = {
apiConfig: {
timeout: 15000,
retry: { retries: 3, delay: 2000, backoff: 2 },
cacheStrategy: 'moderate',
headers: {
'X-Client-Version': '1.0.0',
'X-Request-Priority': 'high'
}
}
};
`
---
#### Data Fetching with Services
`typescript
import {
useCampaigns,
useCampaign,
useCreateCampaign,
useJoinCampaign,
} from '@plyaz/api/services/campaigns';
import { useQueryClient } from '@tanstack/react-query';
import type { ServiceOptions } from '@plyaz/api/services';
function CampaignList() {
const queryClient = useQueryClient();
// Basic query with smart defaults
const { data, isLoading, error } = useCampaigns(
['campaigns', 'active'],
{ status: 'active' }
);
// Query with custom configuration
const { data: searchResults } = useCampaigns(
['campaigns', 'search', searchTerm],
{ search: searchTerm },
// ServiceOptions - API client config
{
apiConfig: {
timeout: 5000,
retry: { retries: 2 },
}
},
// UseQueryOptions - React Query config
{
enabled: searchTerm.length > 2,
staleTime: 30000,
refetchOnWindowFocus: false,
}
);
// Single item query with background caching
const { data: campaign } = useCampaign(
['campaign', campaignId],
{ id: campaignId }
);
// Mutation with comprehensive handlers
const { mutate: createCampaign, isPending } = useCreateCampaign(
// ServiceOptions for API config
{
apiConfig: {
timeout: 15000,
headers: { 'X-Campaign-Source': 'web-app' },
}
},
// Mutation options
{
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['campaigns'] });
toast.success(Campaign "${data.name}" created!);Failed to create: ${error.message}
},
onError: (error) => {
toast.error();
},
onMutate: (variables) => {
// Optimistic update
const previousCampaigns = queryClient.getQueryData(['campaigns']);
queryClient.setQueryData(['campaigns'], (old) => [...old, variables]);
return { previousCampaigns };
},
}
);
// Multiple mutations with shared options
const { mutate: joinCampaign } = useJoinCampaign(undefined, {
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['campaigns', campaignId] });
}
});
if (isLoading) return
if (error) return
return (
#### Hook Configuration Priority
`typescript
// The priority chain (lowest to highest):
// 1. Factory defaults (from createApiQuery/createApiMutation)
// 2. Hook-level defaults (when hook was created)
// 3. ServiceOptions parameter (API config)
// 4. UseQueryOptions parameter (React Query config)// Example showing all levels:
const { data } = useCampaigns(
['campaigns'],
{ status: 'active' }, // Query parameters
{ apiConfig: { timeout: 10000 } }, // Level 3: Service options
{ staleTime: 60000 } // Level 4: React Query options (highest)
);
`#### Monitoring Hooks
`typescript
import { useApiMonitor, useApiNetworkQuality } from '@plyaz/api';function Dashboard() {
const { stats, isHealthy } = useApiMonitor(api);
const { quality, isOnline } = useApiNetworkQuality();
return ;
}
`$3
Service functions provide smart defaults based on HTTP method (GET/POST/PUT/DELETE) and allow granular configuration overrides.
#### Basic Usage
`typescript
import { fetchCampaigns, createCampaign } from '@plyaz/api/services/campaigns';// Simple fetch with smart defaults (interactive caching for lists)
const response = await fetchCampaigns({ status: 'active' });
// Create with realtime strategy (no cache for mutations)
const created = await createCampaign({
name: 'Summer Campaign',
description: 'Q3 promotional campaign'
});
`#### With ServiceOptions Configuration
`typescript
import type { ServiceOptions } from '@plyaz/api/services';// Override API client configuration
const serviceOptions: ServiceOptions = {
apiConfig: {
timeout: 15000, // Custom timeout
retry: { retries: 5, delay: 2000 }, // Aggressive retry
headers: { 'X-Custom': 'value' }, // Additional headers
}
};
const campaigns = await fetchCampaigns(
{ status: 'active', limit: 50 },
serviceOptions
);
// Use different strategies
const realtimeData = await fetchCampaigns(
{ status: 'active' },
{
apiConfig: {
unifiedStrategy: 'realtime', // No cache, always fresh
revalidationStrategy: 'none',
}
}
);
// Mobile-optimized configuration
const mobileData = await fetchCampaigns(
{ status: 'active' },
{
apiConfig: {
unifiedStrategy: 'mobile', // Mobile-friendly caching
networkAware: { enabled: true }, // Adapt to connection
}
}
);
`#### Error Handling Patterns
`typescript
import { isNotFoundError, isValidationError } from '@plyaz/errors';// Pattern 1: Check response.error
const response = await fetchCampaigns({ status: 'active' });
if (response.error) {
if (isNotFoundError(response.error)) {
console.log('No campaigns found');
}
return;
}
console.log('Campaigns:', response.data);
// Pattern 2: Try-catch with throw
try {
const { data, error } = await createCampaign(newCampaign);
if (error) throw error;
console.log('Created:', data);
} catch (err) {
if (isValidationError(err)) {
console.error('Invalid data:', err.message);
}
}
`#### Using Multiple Services
`typescript
import {
fetchCampaign,
fetchCampaignStats,
fetchCampaignParticipants,
} from '@plyaz/api/services/campaigns';// Fetch related data with consistent configuration
const serviceOpts: ServiceOptions = {
apiConfig: { timeout: 10000 }
};
const [campaign, stats, participants] = await Promise.all([
fetchCampaign({ id: '123' }, serviceOpts),
fetchCampaignStats({ id: '123' }, serviceOpts),
fetchCampaignParticipants({ id: '123' }, serviceOpts),
]);
`$3
`typescript
const api = await createApiClient({
onRequest: (config) => {
config.headers['X-Request-ID'] = generateRequestId();
return config;
}, onResponse: (response) => {
console.log(
Request completed in ${response.duration}ms);
return response;
}, onError: (error) => {
if (error.status === 401) {
redirectToLogin();
}
return error;
}
});
`$3
`typescript
import { isNotFoundError, isValidationError } from '@plyaz/errors';const { data, error } = await api.getUser({ id: '123' });
if (error) {
if (isNotFoundError(error)) {
console.log('User not found');
} else if (isValidationError(error)) {
console.log('Invalid parameters');
}
}
`---
🏗️ Architecture
The @plyaz/api package orchestrates 21 internal modules to provide a seamless API experience:
`
Your App → createApiClient() → Smart Features → fetchff → Your API
↓
[Automatic]
• Retry Logic
• Caching
• Deduplication
• Network Adaptation
• Event System
• Performance Tracking
`Want to understand how it works? See the Architecture Overview and Internal Architecture.
---
📚 Documentation
- Usage Guide - Complete usage documentation with examples
- API Reference - Detailed API reference
- Internal Architecture - Deep dive into internal systems
- Confluence Docs - Official documentation
---
🛠️ Development
$3
`bash
Install dependencies
pnpm installStart development mode
pnpm dev
`$3
`bash
pnpm dev # Watch mode development
pnpm build # Build the package
pnpm test # Run tests
pnpm test:watch # Watch mode testing
pnpm test:coverage # Coverage report
pnpm lint # Lint code
pnpm type:check # Type checking
``---
| Package | Purpose | Usage |
|---------|---------|-------|
| @plyaz/types | Type definitions | API interfaces and types |
| @plyaz/errors | Error handling | Standardized error types |
| @plyaz/config | Configuration | API URLs and constants |
---
1. Beginner: Start with Quick Start → Try the examples
2. Intermediate: Read Usage Guide → Learn patterns
3. Advanced: Explore API Reference → Master configuration
4. Expert: Study Internal Architecture → Understand internals
---
This package is part of the Plyaz platform. Please follow the contribution guidelines in the main repository.
---
ISC © Plyaz
---
- Plyaz Platform Documentation
- fetchff Documentation
- React Query Documentation
- TypeScript Documentation