From fc8ffbafbe86b23faa3d9c23732a029b41e9159b Mon Sep 17 00:00:00 2001 From: guang Date: Wed, 24 May 2023 20:40:17 +0800 Subject: [PATCH] feat: custom decorator --- custom-decorator/.eslintrc.js | 25 +++++++ custom-decorator/.gitignore | 35 ++++++++++ custom-decorator/.prettierrc | 4 ++ custom-decorator/README.md | 73 +++++++++++++++++++++ custom-decorator/nest-cli.json | 8 +++ custom-decorator/package.json | 69 +++++++++++++++++++ custom-decorator/src/aaa.decorator.ts | 4 ++ custom-decorator/src/aaa.guard.ts | 18 +++++ custom-decorator/src/app.controller.spec.ts | 22 +++++++ custom-decorator/src/app.controller.ts | 57 ++++++++++++++++ custom-decorator/src/app.module.ts | 10 +++ custom-decorator/src/app.service.ts | 8 +++ custom-decorator/src/bbb.decorator.ts | 11 ++++ custom-decorator/src/ccc.decorator.ts | 7 ++ custom-decorator/src/main.ts | 8 +++ custom-decorator/src/my.decorator.ts | 16 +++++ custom-decorator/test/app.e2e-spec.ts | 24 +++++++ custom-decorator/test/jest-e2e.json | 9 +++ custom-decorator/tsconfig.build.json | 4 ++ custom-decorator/tsconfig.json | 21 ++++++ 20 files changed, 433 insertions(+) create mode 100644 custom-decorator/.eslintrc.js create mode 100644 custom-decorator/.gitignore create mode 100644 custom-decorator/.prettierrc create mode 100644 custom-decorator/README.md create mode 100644 custom-decorator/nest-cli.json create mode 100644 custom-decorator/package.json create mode 100644 custom-decorator/src/aaa.decorator.ts create mode 100644 custom-decorator/src/aaa.guard.ts create mode 100644 custom-decorator/src/app.controller.spec.ts create mode 100644 custom-decorator/src/app.controller.ts create mode 100644 custom-decorator/src/app.module.ts create mode 100644 custom-decorator/src/app.service.ts create mode 100644 custom-decorator/src/bbb.decorator.ts create mode 100644 custom-decorator/src/ccc.decorator.ts create mode 100644 custom-decorator/src/main.ts create mode 100644 custom-decorator/src/my.decorator.ts create mode 100644 custom-decorator/test/app.e2e-spec.ts create mode 100644 custom-decorator/test/jest-e2e.json create mode 100644 custom-decorator/tsconfig.build.json create mode 100644 custom-decorator/tsconfig.json diff --git a/custom-decorator/.eslintrc.js b/custom-decorator/.eslintrc.js new file mode 100644 index 0000000..259de13 --- /dev/null +++ b/custom-decorator/.eslintrc.js @@ -0,0 +1,25 @@ +module.exports = { + parser: '@typescript-eslint/parser', + parserOptions: { + project: 'tsconfig.json', + tsconfigRootDir: __dirname, + sourceType: 'module', + }, + plugins: ['@typescript-eslint/eslint-plugin'], + extends: [ + 'plugin:@typescript-eslint/recommended', + 'plugin:prettier/recommended', + ], + root: true, + env: { + node: true, + jest: true, + }, + ignorePatterns: ['.eslintrc.js'], + rules: { + '@typescript-eslint/interface-name-prefix': 'off', + '@typescript-eslint/explicit-function-return-type': 'off', + '@typescript-eslint/explicit-module-boundary-types': 'off', + '@typescript-eslint/no-explicit-any': 'off', + }, +}; diff --git a/custom-decorator/.gitignore b/custom-decorator/.gitignore new file mode 100644 index 0000000..22f55ad --- /dev/null +++ b/custom-decorator/.gitignore @@ -0,0 +1,35 @@ +# compiled output +/dist +/node_modules + +# Logs +logs +*.log +npm-debug.log* +pnpm-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 \ No newline at end of file diff --git a/custom-decorator/.prettierrc b/custom-decorator/.prettierrc new file mode 100644 index 0000000..dcb7279 --- /dev/null +++ b/custom-decorator/.prettierrc @@ -0,0 +1,4 @@ +{ + "singleQuote": true, + "trailingComma": "all" +} \ No newline at end of file diff --git a/custom-decorator/README.md b/custom-decorator/README.md new file mode 100644 index 0000000..00a13b1 --- /dev/null +++ b/custom-decorator/README.md @@ -0,0 +1,73 @@ +

+ Nest Logo +

+ +[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 +[circleci-url]: https://circleci.com/gh/nestjs/nest + +

A progressive Node.js framework for building efficient and scalable server-side applications.

+

+NPM Version +Package License +NPM Downloads +CircleCI +Coverage +Discord +Backers on Open Collective +Sponsors on Open Collective + + Support us + +

+ + +## Description + +[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. + +## Installation + +```bash +$ npm install +``` + +## Running the app + +```bash +# development +$ npm run start + +# watch mode +$ npm run start:dev + +# production mode +$ npm run start:prod +``` + +## Test + +```bash +# unit tests +$ npm run test + +# e2e tests +$ npm run test:e2e + +# test coverage +$ npm run test:cov +``` + +## Support + +Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support). + +## Stay in touch + +- Author - [Kamil Myƛliwiec](https://kamilmysliwiec.com) +- Website - [https://nestjs.com](https://nestjs.com/) +- Twitter - [@nestframework](https://twitter.com/nestframework) + +## License + +Nest is [MIT licensed](LICENSE). diff --git a/custom-decorator/nest-cli.json b/custom-decorator/nest-cli.json new file mode 100644 index 0000000..f9aa683 --- /dev/null +++ b/custom-decorator/nest-cli.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json.schemastore.org/nest-cli", + "collection": "@nestjs/schematics", + "sourceRoot": "src", + "compilerOptions": { + "deleteOutDir": true + } +} diff --git a/custom-decorator/package.json b/custom-decorator/package.json new file mode 100644 index 0000000..44eec83 --- /dev/null +++ b/custom-decorator/package.json @@ -0,0 +1,69 @@ +{ + "name": "custom-decorator", + "version": "0.0.1", + "description": "", + "author": "", + "private": true, + "license": "UNLICENSED", + "scripts": { + "build": "nest build", + "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", + "start": "nest start", + "start:dev": "nest start --watch", + "start:debug": "nest start --debug --watch", + "start:prod": "node dist/main", + "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" + }, + "dependencies": { + "@nestjs/common": "^9.0.0", + "@nestjs/core": "^9.0.0", + "@nestjs/platform-express": "^9.0.0", + "reflect-metadata": "^0.1.13", + "rxjs": "^7.2.0" + }, + "devDependencies": { + "@nestjs/cli": "^9.0.0", + "@nestjs/schematics": "^9.0.0", + "@nestjs/testing": "^9.0.0", + "@types/express": "^4.17.13", + "@types/jest": "29.5.0", + "@types/node": "18.15.11", + "@types/supertest": "^2.0.11", + "@typescript-eslint/eslint-plugin": "^5.0.0", + "@typescript-eslint/parser": "^5.0.0", + "eslint": "^8.0.1", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-prettier": "^4.0.0", + "jest": "29.5.0", + "prettier": "^2.3.2", + "source-map-support": "^0.5.20", + "supertest": "^6.1.3", + "ts-jest": "29.0.5", + "ts-loader": "^9.2.3", + "ts-node": "^10.0.0", + "tsconfig-paths": "4.2.0", + "typescript": "^4.7.4" + }, + "jest": { + "moduleFileExtensions": [ + "js", + "json", + "ts" + ], + "rootDir": "src", + "testRegex": ".*\\.spec\\.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + }, + "collectCoverageFrom": [ + "**/*.(t|j)s" + ], + "coverageDirectory": "../coverage", + "testEnvironment": "node" + } +} diff --git a/custom-decorator/src/aaa.decorator.ts b/custom-decorator/src/aaa.decorator.ts new file mode 100644 index 0000000..4c08c08 --- /dev/null +++ b/custom-decorator/src/aaa.decorator.ts @@ -0,0 +1,4 @@ +import { SetMetadata } from '@nestjs/common'; + +export const Aaa = (...args: string[]) => SetMetadata('aaa', args); + diff --git a/custom-decorator/src/aaa.guard.ts b/custom-decorator/src/aaa.guard.ts new file mode 100644 index 0000000..b224507 --- /dev/null +++ b/custom-decorator/src/aaa.guard.ts @@ -0,0 +1,18 @@ +import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common'; +import { Reflector } from '@nestjs/core'; +import { Observable } from 'rxjs'; + +@Injectable() +export class AaaGuard implements CanActivate { + @Inject(Reflector) + private reflector: Reflector; + + canActivate( + context: ExecutionContext, + ): boolean | Promise | Observable { + + console.log(this.reflector.get('aaa', context.getHandler())); + + return true; + } +} diff --git a/custom-decorator/src/app.controller.spec.ts b/custom-decorator/src/app.controller.spec.ts new file mode 100644 index 0000000..d22f389 --- /dev/null +++ b/custom-decorator/src/app.controller.spec.ts @@ -0,0 +1,22 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { AppController } from './app.controller'; +import { AppService } from './app.service'; + +describe('AppController', () => { + let appController: AppController; + + beforeEach(async () => { + const app: TestingModule = await Test.createTestingModule({ + controllers: [AppController], + providers: [AppService], + }).compile(); + + appController = app.get(AppController); + }); + + describe('root', () => { + it('should return "Hello World!"', () => { + expect(appController.getHello()).toBe('Hello World!'); + }); + }); +}); diff --git a/custom-decorator/src/app.controller.ts b/custom-decorator/src/app.controller.ts new file mode 100644 index 0000000..e613c89 --- /dev/null +++ b/custom-decorator/src/app.controller.ts @@ -0,0 +1,57 @@ +import { Controller, Get, Headers, Query, SetMetadata, UseGuards, ParseIntPipe } from '@nestjs/common'; +import { Aaa } from './aaa.decorator'; +import { AaaGuard } from './aaa.guard'; +import { AppService } from './app.service'; +import { Bbb } from './bbb.decorator'; +import { Ccc } from './ccc.decorator'; +import { MyHeaders, MyQuery } from './my.decorator'; + +@Controller() +export class AppController { + constructor(private readonly appService: AppService) {} + + @Get() + @SetMetadata('aaa', 'admin') + @UseGuards(AaaGuard) + getHello(): string { + return this.appService.getHello(); + } + + @Get('hello') + @Aaa('admin') + @UseGuards(AaaGuard) + getHello2(): string { + return this.appService.getHello(); + } + + @Bbb('hello2', 'admin') + getHello3(): string { + return this.appService.getHello(); + } + + @Get('hello4') + getHello4(@Ccc() c) { + return c; + } + + @Get('hello5') + getHello5(@Headers('Accept') headers1, @MyHeaders('Accept') headers2) { + console.log(' header1', headers1); + console.log(' header2', headers1); + } + + + @Get('hello6') + getHello6(@Query('aaa') aaa, @MyQuery('bbb') bbb) { + console.log('aaa', aaa); + console.log('bbb', bbb); + } + + @Get('hello7') + getHello7(@Query('aaa', new ParseIntPipe()) aaa, @MyQuery('bbb', new ParseIntPipe()) bbb) { + console.log('aaa', aaa + 1); + console.log('bbb', bbb + 1); + } + + +} diff --git a/custom-decorator/src/app.module.ts b/custom-decorator/src/app.module.ts new file mode 100644 index 0000000..8662803 --- /dev/null +++ b/custom-decorator/src/app.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { AppController } from './app.controller'; +import { AppService } from './app.service'; + +@Module({ + imports: [], + controllers: [AppController], + providers: [AppService], +}) +export class AppModule {} diff --git a/custom-decorator/src/app.service.ts b/custom-decorator/src/app.service.ts new file mode 100644 index 0000000..927d7cc --- /dev/null +++ b/custom-decorator/src/app.service.ts @@ -0,0 +1,8 @@ +import { Injectable } from '@nestjs/common'; + +@Injectable() +export class AppService { + getHello(): string { + return 'Hello World!'; + } +} diff --git a/custom-decorator/src/bbb.decorator.ts b/custom-decorator/src/bbb.decorator.ts new file mode 100644 index 0000000..2d1d8b7 --- /dev/null +++ b/custom-decorator/src/bbb.decorator.ts @@ -0,0 +1,11 @@ +import { applyDecorators, Get, UseGuards } from '@nestjs/common'; +import { Aaa } from './aaa.decorator'; +import { AaaGuard } from './aaa.guard'; + +export function Bbb(path, role) { + return applyDecorators( + Get(path), + Aaa(role), + UseGuards(AaaGuard) + ) +} \ No newline at end of file diff --git a/custom-decorator/src/ccc.decorator.ts b/custom-decorator/src/ccc.decorator.ts new file mode 100644 index 0000000..f50369c --- /dev/null +++ b/custom-decorator/src/ccc.decorator.ts @@ -0,0 +1,7 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; + +export const Ccc = createParamDecorator( + (data: string, ctx: ExecutionContext) => { + return 'ccc'; + }, +); \ No newline at end of file diff --git a/custom-decorator/src/main.ts b/custom-decorator/src/main.ts new file mode 100644 index 0000000..13cad38 --- /dev/null +++ b/custom-decorator/src/main.ts @@ -0,0 +1,8 @@ +import { NestFactory } from '@nestjs/core'; +import { AppModule } from './app.module'; + +async function bootstrap() { + const app = await NestFactory.create(AppModule); + await app.listen(3000); +} +bootstrap(); diff --git a/custom-decorator/src/my.decorator.ts b/custom-decorator/src/my.decorator.ts new file mode 100644 index 0000000..c93281c --- /dev/null +++ b/custom-decorator/src/my.decorator.ts @@ -0,0 +1,16 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; +import { Request } from 'express'; + +export const MyHeaders = createParamDecorator( + (key: string, ctx: ExecutionContext) => { + const request: Request = ctx.switchToHttp().getRequest(); + return key ? request.headers[key] : request.headers; + }, +); + +export const MyQuery = createParamDecorator( + (key: string, ctx: ExecutionContext) => { + const request: Request = ctx.switchToHttp().getRequest(); + return request.query[key]; + }, + ); \ No newline at end of file diff --git a/custom-decorator/test/app.e2e-spec.ts b/custom-decorator/test/app.e2e-spec.ts new file mode 100644 index 0000000..50cda62 --- /dev/null +++ b/custom-decorator/test/app.e2e-spec.ts @@ -0,0 +1,24 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { INestApplication } from '@nestjs/common'; +import * as request from 'supertest'; +import { AppModule } from './../src/app.module'; + +describe('AppController (e2e)', () => { + let app: INestApplication; + + beforeEach(async () => { + const moduleFixture: TestingModule = await Test.createTestingModule({ + imports: [AppModule], + }).compile(); + + app = moduleFixture.createNestApplication(); + await app.init(); + }); + + it('/ (GET)', () => { + return request(app.getHttpServer()) + .get('/') + .expect(200) + .expect('Hello World!'); + }); +}); diff --git a/custom-decorator/test/jest-e2e.json b/custom-decorator/test/jest-e2e.json new file mode 100644 index 0000000..e9d912f --- /dev/null +++ b/custom-decorator/test/jest-e2e.json @@ -0,0 +1,9 @@ +{ + "moduleFileExtensions": ["js", "json", "ts"], + "rootDir": ".", + "testEnvironment": "node", + "testRegex": ".e2e-spec.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + } +} diff --git a/custom-decorator/tsconfig.build.json b/custom-decorator/tsconfig.build.json new file mode 100644 index 0000000..64f86c6 --- /dev/null +++ b/custom-decorator/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] +} diff --git a/custom-decorator/tsconfig.json b/custom-decorator/tsconfig.json new file mode 100644 index 0000000..adb614c --- /dev/null +++ b/custom-decorator/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "declaration": true, + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "allowSyntheticDefaultImports": true, + "target": "es2017", + "sourceMap": true, + "outDir": "./dist", + "baseUrl": "./", + "incremental": true, + "skipLibCheck": true, + "strictNullChecks": false, + "noImplicitAny": false, + "strictBindCallApply": false, + "forceConsistentCasingInFileNames": false, + "noFallthroughCasesInSwitch": false + } +}