Skip to content

Commit

Permalink
fix: adjust addRecord to set the expiry time correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
kkoomen committed Jun 10, 2020
1 parent 77e6d01 commit 5498181
Show file tree
Hide file tree
Showing 11 changed files with 58 additions and 28 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"ioredis": "^4.17.3",
"jest": "^25.1.0",
"lint-staged": "^10.2.9",
"nestjs-throttler": "^0.1.1",
"nestjs-throttler": "^0.2.1",
"nodemon": "^2.0.4",
"prettier": "^1.19.1",
"reflect-metadata": "^0.1.13",
Expand All @@ -79,7 +79,7 @@
"@nestjs/common": "^7.0.0",
"@nestjs/core": "^7.0.0",
"ioredis": "^4.17.3",
"nestjs-throttler": "^0.1.1",
"nestjs-throttler": "^0.2.1",
"reflect-metadata": "^0.1.13"
},
"jest": {
Expand Down
3 changes: 1 addition & 2 deletions src/throttler-storage-redis.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export class ThrottlerStorageRedisService implements ThrottlerStorageRedis {
}

async addRecord(key: string, ttl: number): Promise<void> {
const ttlTime = Date.now() + ttl * 1000;
this.redis.set(`${key}:${ttlTime}`, ttlTime, 'EX', ttlTime);
this.redis.set(`${key}:${Date.now() + ttl * 1000}`, ttl, 'EX', ttl);
}
}
19 changes: 8 additions & 11 deletions test/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import { Module } from '@nestjs/common';
import { ThrottlerModule } from 'nestjs-throttler';
import { ThrottlerStorageRedisService } from '../../src';
import { AppService } from './app.service';
import { APP_GUARD } from '@nestjs/core';
import { ThrottlerGuard } from 'nestjs-throttler';
import { ControllerModule } from './controllers/controller.module';

@Module({
imports: [
ThrottlerModule.forRoot({
limit: 5,
ttl: 60,
storage: new ThrottlerStorageRedisService(),
}),
ControllerModule,
imports: [ControllerModule],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
providers: [AppService],
})
export class AppModule {}
5 changes: 5 additions & 0 deletions test/app/controllers/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,9 @@ export class AppController {
async ignored() {
return this.appService.ignored();
}

@Get('ignore-user-agents')
async ignoreUserAgents() {
return this.appService.ignored();
}
}
3 changes: 3 additions & 0 deletions test/app/controllers/controller.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import { AppService } from '../app.service';
import { AppController } from './app.controller';
import { DefaultController } from './default.controller';
import { LimitController } from './limit.controller';
import { ThrottlerStorageRedisService } from '../../../src';

@Module({
imports: [
ThrottlerModule.forRoot({
limit: 5,
ttl: 60,
ignoreUserAgents: [/throttler-test/g],
storage: new ThrottlerStorageRedisService(),
}),
],
controllers: [AppController, DefaultController, LimitController],
Expand Down
1 change: 0 additions & 1 deletion test/app/controllers/default.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { AppService } from '../app.service';
@Controller('default')
export class DefaultController {
constructor(private readonly appService: AppService) {}

@Get()
getDefault() {
return this.appService.success();
Expand Down
1 change: 0 additions & 1 deletion test/app/controllers/limit.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { AppService } from '../app.service';
@Controller('limit')
export class LimitController {
constructor(private readonly appService: AppService) {}

@Get()
getThrottled() {
return this.appService.success();
Expand Down
8 changes: 6 additions & 2 deletions test/app/main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { FastifyAdapter } from '@nestjs/platform-fastify';
import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule, new ExpressAdapter());
const app = await NestFactory.create(
AppModule,
// new ExpressAdapter(),
new FastifyAdapter(),
);
await app.listen(3000);
}
bootstrap();
20 changes: 19 additions & 1 deletion test/controller.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { INestApplication } from '@nestjs/common';
import { AbstractHttpAdapter } from '@nestjs/core';
import { AbstractHttpAdapter, APP_GUARD } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { FastifyAdapter } from '@nestjs/platform-fastify';
import { Test, TestingModule } from '@nestjs/testing';
import { ThrottlerGuard } from 'nestjs-throttler';
import { ControllerModule } from './app/controllers/controller.module';
import { httPromise } from './utility/httpromise';

Expand All @@ -16,6 +17,12 @@ describe.each`
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [ControllerModule],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
}).compile();

app = moduleFixture.createNestApplication(adapter);
Expand Down Expand Up @@ -45,6 +52,17 @@ describe.each`
'x-ratelimit-reset': /\d+/,
});
});
it('GET /ignore-user-agents', async () => {
const response = await httPromise(appUrl + '/ignore-user-agents', 'GET', {
'user-agent': 'throttler-test/0.0.0',
});
expect(response.data).toEqual({ ignored: true });
expect(response.headers).not.toMatchObject({
'x-ratelimit-limit': '2',
'x-ratelimit-remaining': '1',
'x-ratelimit-reset': /\d+/,
});
});
it('GET /', async () => {
const response = await httPromise(appUrl + '/');
expect(response.data).toEqual({ success: true });
Expand Down
14 changes: 10 additions & 4 deletions test/utility/httpromise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ type HttpMethods = 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';
export function httPromise(
url: string,
method: HttpMethods = 'GET',
headers: Record<string, any> = {},
body?: Record<string, any>,
): Promise<{ data: any; headers: Record<string, any>; status: number }> {
return new Promise((resolve, reject) => {
Expand All @@ -21,15 +22,20 @@ export function httPromise(
status: res.statusCode,
});
});
res.on('error', err =>
reject({
res.on('error', err => {
return reject({
data: err,
headers: res.headers,
status: res.statusCode,
}),
);
});
});
});
req.method = method;

Object.keys(headers).forEach(key => {
req.setHeader(key, headers[key]);
});

switch (method) {
case 'GET':
break;
Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6263,10 +6263,10 @@ neo-async@^2.5.0, neo-async@^2.6.0, neo-async@^2.6.1:
resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.1.tgz#ac27ada66167fa8849a6addd837f6b189ad2081c"
integrity sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw==

nestjs-throttler@^0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/nestjs-throttler/-/nestjs-throttler-0.1.1.tgz#3376ec55a4e4960a222992efd63d08e4dec2519d"
integrity sha512-0RYIOFPUWdlMwdGWsQdUt6Y7mpCxK/rjcnHeikUlOgyDC1seZmzMALXNv8GXpya9To1T8QT+gQwijVRwAeGE3w==
nestjs-throttler@^0.2.1:
version "0.2.1"
resolved "https://registry.yarnpkg.com/nestjs-throttler/-/nestjs-throttler-0.2.1.tgz#c4b16f2fd4dd39985adc4eba548abb3c12eed0be"
integrity sha512-ei3FyvOiv9yqlZPxgB1JTV5lwo4sJfTCeu6MfnzG0VI/JrxbNr5SeeOf8TsoaEiiuWC7TYKk0zrmk+AJwDRm9A==
dependencies:
"@golevelup/nestjs-modules" "^0.4.1"
md5 "^2.2.1"
Expand Down

0 comments on commit 5498181

Please sign in to comment.