A JavaScript/TypeScript client for the LightRate token management API, providing easy-to-use methods for consuming and checking tokens with local bucket management.
npm install lightrate-clientOr with yarn:
yarn add lightrate-clientConfigure the client with your API credentials:
const { configure, getClient } = require('lightrate-client');
configure({
apiKey: 'your_api_key',
applicationId: 'your_application_id', // required
timeout: 30, // optional, defaults to 30 seconds
retryAttempts: 3, // optional, defaults to 3
logger: console // optional, for request logging
});const { LightRateClient, createClient } = require('lightrate-client');
// Simple usage - 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();// Consume tokens by operation
const response = await client.consumeTokens(
'user123', // userIdentifier
1, // tokensRequested
'send_email' // operation
);
// Or consume tokens by path
const response = await client.consumeTokens(
'user123', // userIdentifier
1, // tokensRequested
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(`Tokens consumed successfully. Remaining: ${response.tokensRemaining}`);
} else {
console.log(`Failed to consume tokens: ${response.error}`);
}The client supports local token buckets for improved performance:
// Configure client with default bucket size
const client = new LightRateClient('your_api_key', 'your_application_id', {
defaultLocalBucketSize: 20 // All operations use this bucket size
});
// Consume tokens using local bucket (more efficient)
const result = await client.consumeLocalBucketToken(
'user123', // userIdentifier
'send_email' // operation
);
console.log(`Success: ${result.success}`);
console.log(`Used local token: ${result.usedLocalToken}`);
console.log(`Bucket status: ${JSON.stringify(result.bucketStatus)}`);const { ConsumeTokensRequest } = require('lightrate-client');
// Create a consume tokens request
const request = new ConsumeTokensRequest({
operation: 'send_email',
userIdentifier: 'user123',
tokensRequested: 1
});
// Consume tokens
const response = await client.consumeTokensWithRequest(request);
if (response.success) {
console.log(`Tokens consumed successfully. Remaining: ${response.tokensRemaining}`);
} else {
console.log(`Failed to consume tokens: ${response.error}`);
}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');
async function example() {
try {
// Consume tokens
const consumeResponse = await client.consumeTokens(
'user123',
1,
'send_email'
);
if (consumeResponse.success) {
console.log(`Successfully consumed tokens. Remaining: ${consumeResponse.tokensRemaining}`);
// Proceed with your operation
} else {
console.log(`Failed to consume tokens: ${consumeResponse.error}`);
// 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();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);The client provides comprehensive error handling with specific exception types:
try {
const response = await client.consumeTokens('send_email', undefined, undefined, 'user123', 1);
} 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
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 class for client settings.
Constructor:
new Configuration(options?: Partial<ConfigurationOptions>)Methods:
isValid(): booleantoObject(): Record<string, any>update(options): void
Token bucket for local token management.
Constructor:
new TokenBucket(maxTokens: number)Methods:
hasTokens(): booleanconsumeToken(): booleanconsumeTokens(count): numberrefill(tokensToFetch): numbergetStatus(): TokenBucketStatusreset(): void
configure(options): void- Configure global clientgetClient(): LightRateClient- Get global client instancecreateClient(apiKey, applicationId, options?): LightRateClient- Create new clientreset(): void- Reset global configuration
ConsumeTokensRequestConsumeTokensResponseConsumeLocalBucketTokenResponseRuleConfigurationOptionsClientOptionsTokenBucketStatus
After checking out the repo, run npm install to install dependencies. Then, run npm test to run the tests. You can also run npm run dev for development mode with watch.
To build the project, run npm run build.
Bug reports and pull requests are welcome on GitHub at https://github.com/lightbourne-technologies/lightrate-client-javascript. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
The package is available as open source under the terms of the MIT License.
Everyone interacting in the LightRate Client JavaScript project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.