0.0.2 • Published 5 months ago
libsql-ratelimiter v0.0.2
libsql-ratelimiter
A flexible rate-limiting library built on top of libSQL, providing multiple algorithms (fixed window, sliding window, and token bucket) to control how frequently actions can be performed.
Installation
npm install libsql-ratelimiter
Configuration
Environment variables can be used to set the configuration:
LIBSQL_URL=
LIBSQL_AUTH_TOKEN=
Basic Usage
import { createRateLimiter } from 'libsql-ratelimiter';
async function example() {
const rateLimiter = await createRateLimiter({
url: 'file:./path/to/rate-limit.db', // process.env.LIBSQL_URL
// ...other config like authToken LIBSQL_AUTH_TOKEN can be used
});
// Check if it's initialized
console.log('Is initialized?', rateLimiter.isInitialized());
// Limit requests using the fixed window algorithm
const result = await rateLimiter.limit({
key: 'someUser',
limit: 5, // requests
window: 60, // seconds
algorithm: 'fixed', // 'fixed', 'sliding', or 'token'
});
console.log('Fixed window result:', result);
// Close the client when done
rateLimiter.close();
}
API
createRateLimiter(config?)
Creates and returns a new RateLimiter instance.
limit(options)
Checks if a given request identified by options.key
should be allowed under the specified algorithm. Returns a RateLimitResult object containing:
success
: whether the request is allowedlimit
: max capacityremaining
: remaining limitreset
: milliseconds until limit resets
isInitialized()
Returns a boolean indicating if the underlying table is set up.
close()
Closes the underlying client connection.