Skip to content

Commit

Permalink
feat: add helper to disable limits for the given request
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Feb 1, 2024
1 parent ae2981b commit e9fa96d
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
7 changes: 7 additions & 0 deletions src/http_limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,13 @@ export class HttpLimiter<KnownStores extends Record<string, LimiterManagerStoreF
return this
}

/**
* Returns null to disable rate limiting for the given request
*/
noLimit() {
return null
}

/**
* JSON representation of the http limiter
*/
Expand Down
7 changes: 5 additions & 2 deletions src/limiter_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,11 @@ export class LimiterManager<KnownStores extends Record<string, LimiterManagerSto
*/
define(
name: string,
builder: (ctx: HttpContext, httpLimiter: HttpLimiter<KnownStores>) => HttpLimiter<KnownStores>
): (ctx: HttpContext) => HttpLimiter<KnownStores> {
builder: (
ctx: HttpContext,
httpLimiter: HttpLimiter<KnownStores>
) => HttpLimiter<any> | null | Promise<HttpLimiter<any>> | Promise<null>
): (ctx: HttpContext) => HttpLimiter<any> | null | Promise<HttpLimiter<any>> | Promise<null> {
return (ctx: HttpContext) => {
const limiter = new HttpLimiter(name, ctx, this)
return builder(ctx, limiter)
Expand Down
17 changes: 15 additions & 2 deletions tests/throttle_middleware.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ test.group('Throttle middleware', () => {
})
const ctx = new HttpContextFactory().create()

await apiLimiter(ctx).throttle()
const limiter = await apiLimiter(ctx)
await limiter!.throttle()

try {
await new ThrottleMiddleware().handle(
Expand All @@ -78,14 +79,26 @@ test.group('Throttle middleware', () => {

test('do not throttle request when no limiter is used', async ({ assert }) => {
let nextCalled: boolean = false

const redis = createRedis(['rlflx:api_1']).connection()
const limiterManager = new LimiterManager({
default: 'redis',
stores: {
redis: (options) => new LimiterRedisStore(redis, options),
},
})

const apiLimiter = limiterManager.define('api', (_, limiter) => {
return limiter.noLimit()
})
const ctx = new HttpContextFactory().create()

await new ThrottleMiddleware().handle(
ctx,
() => {
nextCalled = true
},
() => null
apiLimiter
)
assert.isTrue(nextCalled)
})
Expand Down

0 comments on commit e9fa96d

Please sign in to comment.