Skip to content

Commit

Permalink
feat: Initial commit with working prototype
Browse files Browse the repository at this point in the history
  • Loading branch information
kkoomen committed Jun 6, 2020
0 parents commit 0a554d6
Show file tree
Hide file tree
Showing 22 changed files with 8,682 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
lib
35 changes: 35 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
root: true,
env: {
node: true,
jest: true,
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'max-len': ['warn', {
code: 100,
tabWidth: 2,
ignoreComments: false,
ignoreTrailingComments: true,
ignoreUrls: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true
}],
'comma-dangle': ['warn', 'always-multiline'],
},
};
38 changes: 38 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# compiled output
dist
node_modules

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# OS
.DS_Store

# Tests
/coverage
/.nyc_output

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

# VIM
*.swp
*.swo
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"printWidth": 100,
"singleQuote": true,
"trailingComma": "all"
}
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"cSpell.words": [
"ratelimit"
]
}
9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# The MIT License

Copyright 2019 Jay McDoniel, contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# NestJS Throttler Redis Storage Package

This package provides the Redis storage for the
[nestjs-throttler](nestjs-throttler) package.

# Usage

```ts
import { ThrottlerModule } from 'nestjs-throttler';
import { ThrottlerStorageRedisService } from 'nestjs-throttler-storage-redis';

@Module({
imports: [
ThrottlerModule.forRoot({
limit: 5,
ttl: 60,
storage: new ThrottlerStorageRedisService(),
}),
],
})
export class AppModule {}
```

[nestjs-throttler]: https://github.com/jmcdo29/nestjs-throttler
1 change: 1 addition & 0 deletions commitlint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {extends: ['@commitlint/config-conventional']}
4 changes: 4 additions & 0 deletions nest-cli.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}
83 changes: 83 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
{
"name": "nestjs-throttler-storage-redis",
"version": "0.0.1",
"description": "",
"author": "",
"private": false,
"license": "MIT",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib"
],
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start:dev": "nodemon --watch '{src,test/app}/**/*.ts' --ignore '**/*.spec.ts' --exec 'ts-node' test/app/main.ts",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"test:e2e:dev": "yarn test:e2e --watchAll"
},
"dependencies": {},
"devDependencies": {
"@commitlint/cli": "^8.3.5",
"@commitlint/config-conventional": "^8.3.4",
"@nestjs/cli": "^7.0.0",
"@nestjs/platform-express": "^7.0.0",
"@nestjs/platform-fastify": "^7.1.1",
"@nestjs/schematics": "^7.0.0",
"@nestjs/testing": "^7.0.0",
"@types/express": "^4.17.3",
"@types/jest": "25.1.4",
"@types/node": "^13.9.1",
"@types/supertest": "^2.0.8",
"@typescript-eslint/eslint-plugin": "^2.23.0",
"@typescript-eslint/parser": "^2.23.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-import": "^2.20.1",
"husky": "^4.2.5",
"jest": "^25.1.0",
"nodemon": "^2.0.4",
"prettier": "^1.19.1",
"rimraf": "^3.0.2",
"rxjs": "^6.5.4",
"supertest": "^4.0.2",
"ts-jest": "25.2.1",
"ts-loader": "^6.2.1",
"ts-node": "^8.6.2",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.7.4",
"@nestjs/common": "^7.0.0",
"@nestjs/core": "^7.0.0"
},
"peerDependencies": {
"@nestjs/common": "^7.0.0",
"@nestjs/core": "^7.0.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"husky": {
"hooks": {
"pre-commit": "yarn format && yarn lint",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './throttler-storage-redis.service';
21 changes: 21 additions & 0 deletions src/throttler-storage-redis.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as Redis from 'ioredis';

export interface ThrottlerStorageRedis {
/**
* The redis instance.
*/
storage: Redis.Redis;

/**
* Get a record via its key and return all its request ttls.
*/
getRecord(key: string): Promise<number[]>;

/**
* Add a record to the storage. The record will automatically be removed from
* the storage once its TTL has been reached.
*/
addRecord(key: string, ttl: number): Promise<void>;
}

export const ThrottlerStorageRedis = Symbol('ThrottlerStorageRedis');
22 changes: 22 additions & 0 deletions src/throttler-storage-redis.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Injectable } from '@nestjs/common';
import * as Redis from 'ioredis';
import { ThrottlerStorageRedis } from './throttler-storage-redis.interface';

@Injectable()
export class ThrottlerStorageRedisService implements ThrottlerStorageRedis {
storage: Redis.Redis;

constructor(options?: Redis.RedisOptions) {
this.storage = new Redis(options);
}

async getRecord(key: string): Promise<number[]> {
const ttls = (await this.storage.scan(0, 'MATCH', `${key}:*`)).pop();
return (ttls as string[]).map(k => parseInt(k.split(':').pop())).sort();
}

async addRecord(key: string, ttl: number): Promise<void> {
const ttlTime = Date.now() + ttl * 1000;
this.storage.set(`${key}:${ttlTime}`, ttlTime, 'EX', ttlTime);
}
}
3 changes: 3 additions & 0 deletions src/type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { ThrottlerStorageRedis } from './throttler-storage-redis.interface';

export type Type<T extends ThrottlerStorageRedis> = { new (...args: any[]): T };
20 changes: 20 additions & 0 deletions test/app/app.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Controller, Get } from '@nestjs/common';
import { SkipThrottle, Throttle } from 'nestjs-throttler';
import { AppService } from './app.service';

@Controller()
@Throttle(2, 10)
export class AppController {
constructor(private readonly appService: AppService) {}

@Get()
async test() {
return this.appService.success();
}

@Get('ignored')
@SkipThrottle()
async ignored() {
return this.appService.ignored();
}
}
18 changes: 18 additions & 0 deletions test/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Module } from '@nestjs/common';
import { ThrottlerModule } from 'nestjs-throttler';
import { ThrottlerStorageRedisService } from '../../src';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
imports: [
ThrottlerModule.forRoot({
limit: 5,
ttl: 60,
storage: new ThrottlerStorageRedisService(),
}),
AppController,
],
providers: [AppService],
})
export class AppModule {}
12 changes: 12 additions & 0 deletions test/app/app.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
success() {
return { success: true };
}

ignored() {
return { ignored: true };
}
}
9 changes: 9 additions & 0 deletions test/app/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule, new ExpressAdapter());
await app.listen(3000);
}
bootstrap();
9 changes: 9 additions & 0 deletions test/jest-e2e.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": "..",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
8 changes: 8 additions & 0 deletions tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"outDir": "lib"
},
"extends": "./tsconfig.json",
"include": ["src"],
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
14 changes: 14 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"incremental": true
},
"exclude": ["node_modules", "dist"]
}
Loading

0 comments on commit 0a554d6

Please sign in to comment.