JavaScript
A JavaScript/TypeScript client for the LightRate token management API, providing easy-to-use methods for consuming tokens with local bucket management.
Installation
npm install lightrate-clientOr with yarn:
yarn add lightrate-clientConfiguration
Configure the client with your API credentials:
const { configure, getClient } = require('lightrate-client');
configure({
apiKey: 'your_api_key',
applicationId: 'your_application_id',
timeout: 30, // optional, defaults to 30 seconds
retryAttempts: 3, // optional, defaults to 3
logger: console // optional, for request logging
});Basic Usage
const { LightRateClient, createClient } = require('lightrate-client');
// Simple usage - just pass your API key and application id
const client = new LightRateClient('your_api_key', 'your_application_id');
// Or use the convenience method
const client = createClient('your_api_key', 'your_application_id');
// With additional options
const client = new LightRateClient('your_api_key', 'your_application_id', {
timeout: 60,
defaultLocalBucketSize: 10
});
// Or configure globally and use the default client
configure({
apiKey: 'your_api_key',
applicationId: 'your_application_id'
});
const client = getClient();Consuming Tokens
Basic Token Consumption
// Consume tokens by operation (uses local token bucket)
const response = await client.consumeLocalBucketToken(
'user123', // userIdentifier
'send_email' // operation
);
// Or consume tokens by path
const response = await client.consumeLocalBucketToken(
'user123', // userIdentifier
undefined, // operation (not used when path is specified)
'/api/v1/emails/send', // path
'POST' // httpMethod (required when path is specified)
);
if (response.success) {
console.log(`Token consumed from ${response.usedLocalToken ? 'local bucket' : 'server'}`);
} else {
console.log(`Rate limited: No tokens available`);
}Using Local Token Buckets
The client supports local token buckets for improved performance:
// Configure client with bucket sizes
const client = new LightRateClient('your_api_key', 'your_application_id', {
defaultLocalBucketSize: 20
});
// Consume tokens using local bucket (more efficient)
const result = await client.consumeLocalBucketToken(
'user123', // userIdentifier
'send_email' // operation
);
if (result.success) {
console.log(`Success! Used ${result.usedLocalToken ? 'local' : 'server'} token`);
console.log(`Bucket status: ${JSON.stringify(result.bucketStatus)}`);
} else {
console.log('Rate limited: No tokens available');
}Direct HTTP API Usage
For advanced use cases where you need to bypass the local bucket and call the HTTP API directly:
// Direct API call (bypasses local bucket)
const response = await client.consumeTokens(
'user123', // userIdentifier
1, // tokensRequested
'send_email' // operation
);
if (response.tokensConsumed > 0) {
console.log(`Consumed ${response.tokensConsumed} tokens. Remaining: ${response.tokensRemaining}`);
} else {
console.log(`Rate limited: No tokens available`);
}Complete Example
const { LightRateClient } = require('lightrate-client');
// Create a client with your API key and application ID
const client = new LightRateClient('your_api_key', 'your_application_id', {
applicationId: 'your_application_id'
});
async function example() {
try {
// Consume tokens using local bucket
const response = await client.consumeLocalBucketToken(
'user123',
'send_email'
);
if (response.success) {
console.log(`Token consumed from ${response.usedLocalToken ? 'local bucket' : 'server'}`);
// Proceed with your operation
await sendEmailToUser('user123');
} else {
console.log('Rate limit exceeded. Please try again later.');
// Handle rate limiting
}
} catch (error) {
if (error.name === 'UnauthorizedError') {
console.log(`Authentication failed: ${error.message}`);
} else if (error.name === 'TooManyRequestsError') {
console.log(`Rate limited: ${error.message}`);
} else if (error.name === 'APIError') {
console.log(`API Error (${error.statusCode}): ${error.message}`);
} else if (error.name === 'NetworkError') {
console.log(`Network error: ${error.message}`);
}
}
}
example();TypeScript Support
This package includes full TypeScript support with type definitions:
import {
LightRateClient,
ConsumeTokensRequest,
ClientOptions
} from 'lightrate-client';
const client = new LightRateClient('your_api_key', 'your_application_id', {
timeout: 30,
retryAttempts: 3
} as ClientOptions);
const request: ConsumeTokensRequest = {
operation: 'send_email',
userIdentifier: 'user123',
tokensRequested: 1
};
const response = await client.consumeTokensWithRequest(request);Error Handling
The client provides comprehensive error handling with specific exception types:
try {
const response = await client.consumeTokens('user123', 1, 'send_email');
} catch (error) {
if (error.name === 'UnauthorizedError') {
console.log('Authentication failed:', error.message);
} else if (error.name === 'NotFoundError') {
console.log('Resource not found:', error.message);
} else if (error.name === 'APIError') {
console.log(`API Error (${error.statusCode}):`, error.message);
} else if (error.name === 'NetworkError') {
console.log('Network error:', error.message);
} else if (error.name === 'TimeoutError') {
console.log('Request timed out:', error.message);
}
}Available Error Types
LightRateError- Base error classConfigurationError- Configuration-related errorsAuthenticationError- Authentication-related errorsAPIError- Base API error classBadRequestError- 400 errorsUnauthorizedError- 401 errorsForbiddenError- 403 errorsNotFoundError- 404 errorsUnprocessableEntityError- 422 errorsTooManyRequestsError- 429 errorsInternalServerError- 500 errorsServiceUnavailableError- 503 errorsNetworkError- Network-related errorsTimeoutError- Request timeout errors
API Reference
Classes
LightRateClient
Main client class for interacting with the LightRate API.
Constructor:
new LightRateClient(apiKey: string, applicationId: string, options?: ClientOptions)Methods:
consumeTokens(userIdentifier, tokensRequested, operation?, path?, httpMethod?): Promise<ConsumeTokensResponse>consumeLocalBucketToken(userIdentifier, operation?, path?, httpMethod?): Promise<ConsumeLocalBucketTokenResponse>consumeTokensWithRequest(request): Promise<ConsumeTokensResponse>getAllBucketStatuses(): Record<string, any>resetAllBuckets(): voidgetConfiguration(): Configuration
Configuration
Configuration class for client settings.
Constructor:
new Configuration(options?: Partial<ConfigurationOptions>)Methods:
isValid(): booleantoObject(): Record<string, any>update(options): void
TokenBucket
Token bucket for local token management.
Constructor:
new TokenBucket(maxTokens: number)Methods:
hasTokens(): booleanconsumeToken(): booleanconsumeTokens(count): numberrefill(tokensToFetch): numbergetStatus(): TokenBucketStatusreset(): void
Global Functions
configure(options): void- Configure global clientgetClient(): LightRateClient- Get global client instancecreateClient(apiKey, options?): LightRateClient- Create new clientreset(): void- Reset global configuration
Types
ConsumeTokensRequestConsumeTokensResponseConsumeLocalBucketTokenResponseRuleConfigurationOptionsClientOptionsTokenBucketStatus
Last updated on