Skip to main content
zerotal

Documentation


Documentation / @zerotal/core / index / LimiterDefinition

Class: LimiterDefinition

Defined in: middleware/RateLimiter.ts:14

Fluent rate-limiter definition. Build one via RateLimiter.for('name') then register with .register().

Constructors

Constructor

new LimiterDefinition(_name): LimiterDefinition

Defined in: middleware/RateLimiter.ts:19

Parameters

_name

string

Returns

LimiterDefinition

Methods

limit()

limit(max): this

Defined in: middleware/RateLimiter.ts:22

Maximum number of requests in the window.

Parameters

max

number

Returns

this


every()

every(seconds): this

Defined in: middleware/RateLimiter.ts:28

Window duration in seconds.

Parameters

seconds

number

Returns

this


by()

by(fn): this

Defined in: middleware/RateLimiter.ts:34

Custom key resolver — defaults to client IP.

Parameters

fn

(ctx) => string

Returns

this


byUser()

byUser(): this

Defined in: middleware/RateLimiter.ts:47

Key by the authenticated user's ID. Unauthenticated requests fall back to the client IP so they are still rate-limited independently from each other.

Returns

this

Example

RateLimiter.for('api').limit(1000).every(3600).byUser().register();

byApiKey()

byApiKey(header?): this

Defined in: middleware/RateLimiter.ts:62

Key by an API key header value. Requests that omit the header fall back to client IP.

Parameters

string = "x-api-key"

Returns

this

Example

RateLimiter.for('api').limit(500).every(60).byApiKey('x-api-key').register();

byIp()

byIp(): this

Defined in: middleware/RateLimiter.ts:75

Key by client IP address (explicitly named; this is already the default). Useful to make intent explicit when combining with other .by*() calls through the fluent API.

Returns

this


register()

register(): this

Defined in: middleware/RateLimiter.ts:81

Register this limiter with the global RateLimiter registry.

Returns

this


toMiddlewareClass()

toMiddlewareClass(): () => ThrottleMiddleware

Defined in: middleware/RateLimiter.ts:95

Build a dedicated ThrottleMiddleware subclass for this definition.

A subclass rather than a bare instance for two reasons. First, routes and Pipeline.through() take middleware classes and call new PipeClass(); handing them an instance threw TypeError: ThrottleMiddleware is not a constructor on every request. Second, hit counters are keyed on the concrete class, so giving each named limiter its own subclass is what keeps login and api counting into separate buckets.

Returns

() => ThrottleMiddleware


toMiddleware()

toMiddleware(): ThrottleMiddleware

Defined in: middleware/RateLimiter.ts:111

Build a ThrottleMiddleware instance from this definition.

Prefer toMiddlewareClass for anything that goes into a route or a pipeline. This remains for the imperative API (RateLimiter.tooManyAttempts, resetFor), which needs a live object; it shares counters with the class because both are the same subclass.

Returns

ThrottleMiddleware