Skip to content
This repository has been archived by the owner on Nov 23, 2022. It is now read-only.

Commit

Permalink
provide customResponseSchema feature
Browse files Browse the repository at this point in the history
  • Loading branch information
onur-ozkan committed Jan 24, 2021
1 parent 2035b9d commit 498a829
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 4 deletions.
1 change: 1 addition & 0 deletions lib/default-options.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,6 @@ describe('defaultRateLimiterOptions', () => {
expect(Object.keys(defaultRateLimiterOptions.indexKeyPrefix).length).toBe(0)
expect(defaultRateLimiterOptions.maxQueueSize).toBe(100)
expect(defaultRateLimiterOptions.errorMessage).toBe('Rate limit exceeded')
expect(defaultRateLimiterOptions.customResponseSchema).toBeUndefined()
})
})
3 changes: 2 additions & 1 deletion lib/default-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@ export const defaultRateLimiterOptions: RateLimiterOptions = {
execEvenlyMinDelayMs: undefined,
indexKeyPrefix: {},
maxQueueSize: 100,
errorMessage: 'Rate limit exceeded'
errorMessage: 'Rate limit exceeded',
customResponseSchema: undefined
}
5 changes: 3 additions & 2 deletions lib/rate-limiter.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,9 @@ export class RateLimiterInterceptor implements NestInterceptor {
}
} catch (rateLimiterResponse) {
response.header('Retry-After', Math.ceil(rateLimiterResponse.msBeforeNext / 1000))
if (typeof this.options.createErrorBody === 'function') {
throw new HttpException(this.options.createErrorBody(rateLimiterResponse), HttpStatus.TOO_MANY_REQUESTS)
if (typeof this.spesificOptions?.customResponseSchema === 'function' || typeof this.options.customResponseSchema === 'function') {
var errorBody = this.spesificOptions?.customResponseSchema || this.options.customResponseSchema;
throw new HttpException(errorBody(rateLimiterResponse), HttpStatus.TOO_MANY_REQUESTS)
} else {
throw new HttpException(this.spesificOptions?.errorMessage || this.options.errorMessage, HttpStatus.TOO_MANY_REQUESTS)
}
Expand Down
2 changes: 1 addition & 1 deletion lib/rate-limiter.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export interface RateLimiterOptions {
indexKeyPrefix?: {}
maxQueueSize?: number
errorMessage?: string
createErrorBody?: (rateLimiterResponse: RateLimiterRes) => {}
customResponseSchema?: (rateLimiterResponse: RateLimiterRes) => {}
}

export interface RateLimiterOptionsFactory {
Expand Down

0 comments on commit 498a829

Please sign in to comment.