A comprehensive TypeScript API client library for the Bluefly AI Platform with advanced features for production-grade applications.
Versatile Protocol Support: REST and GraphQL clients in one package
Advanced Caching System
Robust Resilience
Observability & Telemetry
Developer Experience
# With npm
npm install @bluefly/api-client
# With yarn
yarn add @bluefly/api-client
# With pnpm
pnpm add @bluefly/api-client
import { RestClient } from '@bluefly/api-client';
// Create a client
const client = new RestClient({
baseUrl: 'https://api.example.com',
timeout: 30000, // 30 seconds
});
// Make requests
async function fetchData() {
try {
const response = await client.get('/users');
console.log(response.data);
} catch (error) {
console.error('API request failed:', error);
}
}
// POST with data
async function createUser(userData) {
try {
const response = await client.post('/users', userData);
return response.data;
} catch (error) {
console.error('Failed to create user:', error);
throw error;
}
}
import { GraphQLClient } from '@bluefly/api-client';
// Create a GraphQL client
const client = new GraphQLClient({
baseUrl: 'https://api.example.com/graphql',
});
// Execute a query
async function getUser(id) {
const query = `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`;
const response = await client.query(query, { id });
return response.data.user;
}
// Execute a mutation
async function updateUser(id, userData) {
const mutation = `
mutation UpdateUser($id: ID!, $input: UserInput!) {
updateUser(id: $id, input: $input) {
id
name
email
}
}
`;
const response = await client.mutate(mutation, {
id,
input: userData
});
return response.data.updateUser;
}
import {
RestClient,
bearerTokenInterceptor,
requestLoggingInterceptor,
responseLoggingInterceptor,
createAdvancedRetryInterceptor
} from '@bluefly/api-client';
const client = new RestClient({
baseUrl: 'https://api.example.com',
});
// Add authentication
client.addRequestInterceptor(bearerTokenInterceptor('your-token'));
// Add logging
client.addRequestInterceptor(requestLoggingInterceptor({ logHeaders: true }));
client.addResponseInterceptor(responseLoggingInterceptor());
// Add retry logic
client.addErrorInterceptor(
createAdvancedRetryInterceptor({
maxRetries: 5,
retryableStatusCodes: [429, 500, 502, 503, 504],
jitterFactor: 0.3,
})
);
import {
RestClient,
CacheManager,
InMemoryCache
} from '@bluefly/api-client';
// Create a cache manager
const cache = new CacheManager({
strategy: new InMemoryCache(),
defaultTtl: 300000, // 5 minutes
});
// Make cached requests
async function getUserWithCaching(id) {
const cacheKey = `user:${id}`;
// Try to get from cache first
const cachedUser = await cache.get(cacheKey);
if (cachedUser) {
return cachedUser;
}
// Fetch from API
const response = await client.get(`/users/${id}`);
const user = response.data;
// Cache the result
await cache.set(cacheKey, user);
return user;
}
For advanced caching with multiple storage tiers:
import {
HierarchicalCacheManager,
InMemoryCache,
RedisCache,
DiskCache
} from '@bluefly/api-client';
// Create a hierarchical cache
const cache = new HierarchicalCacheManager({
memory: {
maxSize: 1000,
ttl: 300 // 5 minutes
},
redis: {
url: 'redis://localhost:6379',
ttl: 3600 // 1 hour
},
disk: {
basePath: './cache',
ttl: 86400, // 24 hours
compress: true
}
});
// Get a value (tries memory → redis → disk)
const value = await cache.get('my-key');
// Set a value in all tiers
await cache.set('my-key', { data: 'value' }, {
ttl: 3600,
level: 'all' // or 'memory', 'redis', 'disk'
});
<!-- UMD build -->
<script src="https://cdn.jsdelivr.net/npm/@bluefly/api-client/dist/bfapiclient.browser.min.js"></script>
<script>
const client = new BFAPIClient.createBrowserClient({
baseUrl: 'https://api.example.com'
});
client.get('/api/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
</script>
<!-- ESM build -->
<script type="module">
import { createBrowserClient } from 'https://cdn.jsdelivr.net/npm/@bluefly/api-client/dist/bfapiclient.browser.esm.min.js';
const client = createBrowserClient({
baseUrl: 'https://api.example.com'
});
async function fetchData() {
try {
const response = await client.get('/api/data');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
fetchData();
</script>
import { RestClient } from '@bluefly/api-client';
import { trace, context, SpanStatusCode } from '@opentelemetry/api';
const client = new RestClient({
baseUrl: 'https://api.example.com',
telemetry: {
serviceName: 'my-service',
environment: 'production',
enabled: true,
}
});
// In your application code
async function processOrder(orderId) {
// Create a span
const span = trace.getTracer('my-app').startSpan('process-order');
// Use the span in a context
return context.with(trace.setSpan(context.active(), span), async () => {
try {
// API call will automatically link to this span
const response = await client.get(`/orders/${orderId}`);
span.setStatus({ code: SpanStatusCode.OK });
return response.data;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message,
});
throw error;
} finally {
span.end();
}
});
}
import {
RestClient,
GenerateRequest,
GenerateResponse
} from '@bluefly/api-client';
const client = new RestClient({
baseUrl: 'https://api.example.com',
});
async function generateText(prompt: string): Promise<string> {
const request: GenerateRequest = {
prompt,
maxTokens: 100,
temperature: 0.7,
};
const response = await client.post<GenerateResponse>(
'/generate',
request
);
return response.data.text;
}
import {
RestClient,
createResilientRetryInterceptor
} from '@bluefly/api-client';
const client = new RestClient({
baseUrl: 'https://api.example.com',
});
// Add advanced retry logic
client.addErrorInterceptor(
createResilientRetryInterceptor({
// Maximum number of retry attempts
maxRetries: 5,
// Base delay between retries (ms)
baseDelayMs: 100,
// Maximum delay between retries (ms)
maxDelayMs: 30000,
// Exponential backoff factor
backoffFactor: 2,
// Random jitter factor (0-1)
jitterFactor: 0.25,
// HTTP status codes that should trigger a retry
retryableStatusCodes: [408, 425, 429, 500, 502, 503, 504, 507, 509],
// Overall timeout for retry sequence
timeout: 60000,
// Whether to retry network errors
retryNetworkErrors: true,
})
);
For detailed API documentation, run:
npm run docs
npm run serve:docs
The browser build is compatible with:
Error Handling
Performance Optimization
Security
Maintainability
MIT License - see LICENSE file for details
Generated using TypeDoc