├── .eslintignore ├── .eslintrc ├── .github └── workflows │ ├── build.yml │ ├── codeql-analysis.yml │ ├── nodejs.yml │ └── publish.yml ├── .gitignore ├── .npmignore ├── .travis.yml ├── README.md ├── app.js ├── app └── extend │ └── helper.js ├── appveyor.yml ├── config └── config.default.js ├── index.d.ts ├── index.js ├── lib ├── common │ ├── class-serializer.interceptor.js │ ├── index.js │ ├── parse-int.pipe.js │ └── validation.pipe.js ├── constants.js ├── decorator.js ├── decorator_manager.js ├── exceptions │ ├── constant.js │ └── exception.js ├── loader │ ├── egg_loader.js │ └── file_loader.js ├── proxy │ ├── context_creator.js │ ├── exception_handler.js │ ├── router_param_factory.js │ └── router_proxy.js └── utils.js ├── package.json └── test ├── 1.jpg ├── 2.jpg ├── fixtures └── apps │ └── pigapp │ ├── app │ ├── controller │ │ ├── context.js │ │ ├── controller_options.js │ │ ├── dep │ │ │ ├── dep.js │ │ │ └── innerdep │ │ │ │ └── dep01.js │ │ ├── exception.js │ │ ├── exportcommon.js │ │ ├── filter.js │ │ ├── global.js │ │ ├── guard.js │ │ ├── header.js │ │ ├── helper.js │ │ ├── httpcode.js │ │ ├── httpverb.js │ │ ├── interceptot.js │ │ ├── middleware_a.js │ │ ├── middleware_b.js │ │ ├── middleware_resource.js │ │ ├── middlware_rest.js │ │ ├── other.js │ │ ├── parent_controller.js │ │ ├── parent_rest_controller.js │ │ ├── pipe.js │ │ ├── pipetest.js │ │ ├── render.js │ │ ├── resources.js │ │ ├── serializer.js │ │ ├── upload.js │ │ └── user.js │ ├── core │ │ └── base.js │ ├── middleware │ │ ├── loga.js │ │ └── logb.js │ ├── router.js │ └── view │ │ └── list.tpl │ ├── config │ ├── config.default.js │ └── plugin.js │ └── package.json └── pig.test.js /.eslintignore: -------------------------------------------------------------------------------- 1 | test/fixtures 2 | coverage 3 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint-config-egg", 3 | } 4 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: [push, pull_request] 7 | 8 | jobs: 9 | Runner: 10 | runs-on: ${{ matrix.os }} 11 | strategy: 12 | matrix: 13 | os: [ubuntu-latest, macOS-latest] 14 | node-version: [10, 12, 14] 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Use Node.js ${{ matrix.node-version }} 18 | uses: actions/setup-node@v1 19 | with: 20 | node-version: ${{ matrix.node-version }} 21 | - name: Install Dependencies 22 | run: | 23 | npm install 24 | - name: Continuous integration 25 | run: npm run ci 26 | - name: Code Coverage 27 | run: | 28 | npm install codecov -g 29 | codecov 30 | env: 31 | CI: true 32 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '18 22 * * 0' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://git.io/codeql-language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v2 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v1 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 52 | 53 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 54 | # If this step fails, then you should remove it and run the build manually (see below) 55 | - name: Autobuild 56 | uses: github/codeql-action/autobuild@v1 57 | 58 | # ℹ️ Command-line programs to run using the OS shell. 59 | # 📚 https://git.io/JvXDl 60 | 61 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 62 | # and modify them (or add more) to build your code if your project 63 | # uses a compiled language 64 | 65 | #- run: | 66 | # make bootstrap 67 | # make release 68 | 69 | - name: Perform CodeQL Analysis 70 | uses: github/codeql-action/analyze@v1 71 | -------------------------------------------------------------------------------- /.github/workflows/nodejs.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ${{ matrix.os }} 16 | 17 | strategy: 18 | matrix: 19 | node-version: [10.x, 12.x, 14.x] 20 | os: [ubuntu-latest, windows-latest, macos-latest] 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v1 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | - run: npm i -g npminstall && npminstall 29 | - run: npm run ci 30 | env: 31 | CI: true 32 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages 3 | 4 | name: Node.js Package 5 | 6 | on: 7 | push: 8 | tags: 9 | - 'v*' 10 | release: 11 | types: [published] 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v2 18 | - uses: actions/setup-node@v1 19 | with: 20 | node-version: 12 21 | - run: npm install 22 | - run: npm test 23 | 24 | publish-npm: 25 | needs: build 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v2 29 | - uses: actions/setup-node@v1 30 | with: 31 | node-version: 12 32 | registry-url: https://registry.npmjs.org/ 33 | - run: npm publish 34 | env: 35 | NODE_AUTH_TOKEN: ${{secrets.NPM_AUTH_TOKEN}} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | logs/ 2 | npm-debug.log 3 | node_modules/ 4 | coverage/ 5 | .idea/ 6 | run/ 7 | .DS_Store 8 | *.swp 9 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | logs/ 2 | npm-debug.log 3 | node_modules/ 4 | coverage/ 5 | .idea/ 6 | run/ 7 | .DS_Store 8 | *.swp 9 | 10 | .config 11 | .coveralls.yml 12 | .editorconfig 13 | .eslintignore 14 | .eslintrc.json 15 | .githooks 16 | .nyc_output 17 | .travis.yml 18 | .vscode 19 | .github 20 | 21 | appveyor.yml 22 | commitlint.config.js 23 | demo 24 | npm-shrinkwrap.json 25 | rollup.config.js 26 | src 27 | test 28 | test_browser* 29 | tsconfig.json 30 | tsconfig.cjs.json 31 | tsconfig.*.json 32 | tslint.json 33 | 34 | !/asset/.config 35 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | 2 | language: node_js 3 | node_js: 4 | - '10' 5 | - '12' 6 | - '14' 7 | before_install: 8 | - npm i npminstall -g 9 | install: 10 | - npminstall 11 | script: 12 | - npm run ci 13 | after_script: 14 | - npminstall codecov && codecov 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # egg-pig 2 | nest.js in egg. 3 | 4 | [![NPM version][npm-image]][npm-url] 5 | [![build status][travis-image]][travis-url] 6 | [![coverage][coverage-image]][coverage-url] 7 | 8 | [npm-image]: https://img.shields.io/npm/v/egg-pig.svg?style=flat-square 9 | [npm-url]: https://npmjs.org/package/egg-pig 10 | [travis-image]: https://travis-ci.org/yviscool/egg-pig.svg?branch=master 11 | [travis-url]: https://travis-ci.org/yviscool/egg-pig 12 | [coverage-url]: https://codecov.io/gh/yviscool/egg-pig 13 | [coverage-image]: https://codecov.io/gh/yviscool/egg-pig/branch/master/graph/badge.svg 14 | 15 | * [Installation](#installation) 16 | - [Config](#Config) 17 | * [Usage](#usage) 18 | + [Controller](#controller) 19 | + [Return value](#return-value) 20 | + [Param Decorators](#param-decorators) 21 | + [Route name](#route-name) 22 | + [Restful](#restful) 23 | + [Multiple Middleware](#multiple-middleware) 24 | + [Render Header](#render-header) 25 | * [Guard](#guard) 26 | * [Pipe](#pipe) 27 | + [Build-in ValidationPipe](#build-in-balidationpipe) 28 | * [Interceptor](#interceptor) 29 | + [Build-in interceptor](#build-in-interceptor) 30 | * [Filter](#filter) 31 | * [Tips](#tips) 32 | * [Global](#global) 33 | * [Custom Decorators](#custom-decorators) 34 | 35 | ## Installation 36 | 37 | ```bash 38 | $ npm i egg-pig --save 39 | ``` 40 | 41 | ### Config 42 | 43 | ```js 44 | // app/config/plugin.js 45 | eggpig: { 46 | enable: true, 47 | package: 'egg-pig' 48 | } 49 | ``` 50 | 51 | ## Usage 52 | 53 | ### Controller 54 | 55 | ```js 56 | import { IService, EggAppConfig, Application, Context } from 'egg'; 57 | import { Controller, Get, Post } from 'egg-pig'; 58 | 59 | @Controller('cats') // => /cats 60 | export class CatsController { 61 | 62 | constructor( 63 | private ctx: Context, 64 | private app: Application, 65 | private config: EggAppConfig, 66 | private service: IService, 67 | ) { } 68 | 69 | @Get() // => router.get('/cats', index) 70 | async index() { 71 | this.ctx.body = 'index'; 72 | // or return 'index' 73 | } 74 | 75 | @Get('get') // => router.get('/cats/get', foo) 76 | async foo() { 77 | return 'add' 78 | // or this.ctx.body = 'add'; 79 | } 80 | 81 | @Post('/add') // => router.post('/cats/add', bar) 82 | async bar(@Body() body) { 83 | return body; 84 | // or this.ctx.body = body; 85 | } 86 | 87 | } 88 | ``` 89 | 90 | another way 91 | 92 | ```js 93 | import { BaseContextClass } from 'egg'; 94 | import { Controller, Get, Post } from 'egg-pig'; 95 | 96 | @Controller('cats') // => /cats 97 | export class CatsController extends BaseContextClass{ 98 | 99 | @Get() 100 | async foo() { 101 | return await this.service.foo.bar(); 102 | } 103 | } 104 | ``` 105 | 106 | ### return value 107 | 108 | ```js 109 | @Controller('cats') 110 | export class CatsController { 111 | 112 | @Get('/add') // router.get('/cats/add', foo) 113 | async foo() { 114 | return 'zjl'; // this.ctx.body = 'zjl; 115 | } 116 | 117 | @Get('bar') // router.get('/cats/foo', bar) 118 | async bar() { 119 | return await this.service.xxx.yyy(); // this.ctx.body = ''; 120 | } 121 | } 122 | ``` 123 | use return value replace ctx.body; 124 | 125 | 126 | ### Param Decorators 127 | ```js 128 | import { Context, Request, Response, Param, Query, Body, Session, Headers, Res, Req, UploadedFile, UploadedFiles, UploadedFileStream, UploadedFilesStream } from 'egg-pig'; 129 | 130 | @Controller('cats') 131 | export class CatsController { 132 | public async foo( 133 | @Request() req, 134 | @Response() res, 135 | @Req() req, // alias 136 | @Res() res,// alias 137 | @Param() param, 138 | @Query() query, 139 | @Body() body, 140 | @Session() session, 141 | @Headers() headers, 142 | @UploadedFile() file, 143 | @UploadedFiles() fils, 144 | @UploadedFileStream() stream, 145 | @UploadedFilesStream() parts 146 | ) { 147 | // req= this.ctx.request; 148 | // res = this.ctx.response; 149 | // param = this.ctx.params; 150 | // query = this.ctx.query; 151 | // body = this.ctx.request.body; 152 | // session = this.ctx.session; 153 | // headers = this.ctx.headers; 154 | // file = this.ctx.request.files[0] 155 | // files = this.ctx.request.files; 156 | // stream = await this.ctx.getFileStream(); 157 | // parts = this.ctx.multipart(); 158 | } 159 | } 160 | ``` 161 | 162 | 163 | ### route name 164 | 165 | ```js 166 | import { Controller, Get, Param } from 'egg-pig'; 167 | 168 | @Controller('cats') 169 | export class CatsController { 170 | 171 | @Get(':id',{ routerName: 'cats'}) // router.get('cats', '/cats/:id', foo) 172 | async foo(@Param('id') param) { 173 | return param; 174 | } 175 | } 176 | ``` 177 | 178 | ### restful 179 | 180 | ```js 181 | import { Resources, Get } from 'egg-pig'; 182 | 183 | @Resources('cats') // => router.resources(''cats', /cats', CastController) 184 | // or @Restful('cats') 185 | export class CatsController { 186 | 187 | async index() { 188 | return 'index'; 189 | } 190 | 191 | async new() { 192 | return 'new'; 193 | } 194 | 195 | @Get('/add') // router.get('/cats/add', add) 196 | async add() { 197 | return 'add'; 198 | } 199 | 200 | } 201 | ``` 202 | You can also use `@Restful()` Decorator, the same as Resources; 203 | 204 | ### multiple-middleware 205 | 206 | 207 | 1. use decorator router options 208 | 209 | ```ts 210 | @Controller('/', {middleware: ['homeMiddleware']}) // this.app.middleware['homeMiddleware'] 211 | export class Test { 212 | 213 | @Get('/', {middleware: ['apiMiddleware']}) // this.app.middleware['apiMiddleware'] 214 | async index() { 215 | const ctx = this.ctx; 216 | return ctx.home + ctx.api; 217 | } 218 | 219 | } 220 | ``` 221 | 222 | 2. use koa-router feature 223 | 224 | ```js 225 | // router.ts 226 | export default (app:Application) => { 227 | 228 | const { router } = app; 229 | 230 | router.get('/cats/add', async (_,next) => { 231 | console.log('this is middleware'); 232 | return next(); 233 | }); 234 | 235 | }; 236 | 237 | 238 | // cats.ts 239 | @Controller('cats') 240 | export class CatsController { 241 | 242 | @Get('/add') 243 | async foo(){ 244 | this.ctx.body = 'add'; 245 | } 246 | } 247 | 248 | ``` 249 | 250 | ### render-header 251 | 252 | ```js 253 | import { Render,Controller, Get, Header } from 'egg-pig'; 254 | 255 | @Controller('home') 256 | export class HomeController { 257 | 258 | @Get() // /home 259 | @Render('list.tpl') 260 | async foo() { 261 | const dataList = { 262 | list: [ 263 | { id: 1, title: 'this is news 1', url: '/news/1' }, 264 | { id: 2, title: 'this is news 2', url: '/news/2' } 265 | ] 266 | }; 267 | return dataList; 268 | } 269 | 270 | @Header('ETag','123') 271 | @Get('etag') 272 | async bar() { 273 | ... 274 | } 275 | 276 | @Header({ 277 | 'Etag': '1234', 278 | 'Last-Modified': new Date(), 279 | }) 280 | @Get('other') 281 | async baz() { 282 | ... 283 | } 284 | } 285 | ``` 286 | 287 | ## use 288 | you can see [nest.js](https://docs.nestjs.com/). 289 | 290 | ### Guard 291 | 292 | ```js 293 | import { Injectable, CanActivate, ExecutionContext, UseGuards } from 'egg-pig'; 294 | import { Observable } from 'rxjs/Observable'; 295 | 296 | @Injectable() 297 | class XXGuard extends CanActivate{ 298 | canActivate(context: ExecutionContext) 299 | : boolean | Promise | Observable { 300 | return true; 301 | } 302 | } 303 | 304 | @UseGuards(XXGuard) 305 | export class HomeController { 306 | // @UseGuards(XXGuard) 307 | public async foo() { 308 | // some logic 309 | } 310 | } 311 | ``` 312 | 313 | 314 | ### Pipe 315 | ```js 316 | import { PipeTransform, Injectable, ArgumentMetadata, UsePipes, Param, Query, Body } from 'egg-pig'; 317 | 318 | @Injectable() 319 | class XXPipe extends PipeTransform{ 320 | async transform(value: any, metadata: ArgumentMetadata) { 321 | return value; 322 | } 323 | } 324 | 325 | @UsePipes(XXPipe) 326 | export class HomeController { 327 | // @UsePipes(XXPipe) 328 | async foo(@Param('xx', XXPipe) param; @Body('xx', XXPipe) body, @Query(XXPipe) quey) { 329 | // some logic 330 | } 331 | } 332 | ``` 333 | 334 | #### Build-in ValidationPipe 335 | 336 | ```js 337 | import { ParseIntPipe, ValidationPipe } from 'egg-pig'; 338 | import { IsInt, IsString, Length } from "class-validator"; 339 | 340 | class User { 341 | 342 | @IsInt() 343 | age: number; 344 | 345 | @Length(2, 10) 346 | firstName: string; 347 | 348 | @IsString() 349 | lastName: string; 350 | 351 | getName() { 352 | return this.firstName + ' ' + this.lastName; 353 | } 354 | 355 | } 356 | 357 | @Controller('pipetest') 358 | export class PipetestController { 359 | 360 | @Get('parseint') 361 | async foo(@Query('id', ParseIntPipe) id) { 362 | return id; 363 | } 364 | 365 | @Post('validation') 366 | async bar(@Body(new ValidationPipe({ transform: true })) user: User) { 367 | return user.getName(); 368 | } 369 | 370 | } 371 | ``` 372 | 373 | Notice You may find more information about the 374 | [class-validator](https://github.com/typestack/class-validator)/ 375 | [class-transformer](https://github.com/typestack/class-transformer) 376 | 377 | 378 | ### Interceptor 379 | 380 | ```js 381 | import { EggInterceptor, UseInterceptors, Interceptor} from 'egg-pig'; 382 | import { Injectable, EggInterceptor, ExecutionContext, CallHandler } from 'egg-pig'; 383 | import { Observable } from 'rxjs/Observable'; 384 | import { tap } from 'rxjs/operators'; 385 | 386 | @Injectable() 387 | class LoggingInterceptor extends EggInterceptor { 388 | intercept( 389 | context: ExecutionContext, 390 | call$: CallHandler, 391 | ): Observable { 392 | console.log('Before...'); 393 | const now = Date.now(); 394 | return call$.handle().pipe( 395 | tap(() => console.log(`After... ${Date.now() - now}ms`)), 396 | ); 397 | } 398 | } 399 | 400 | @UseInterceptors(LoggingInterceptor) 401 | export class HomeController { 402 | 403 | //@UseInterceptors(LoggingInterceptor) 404 | public async foo() { 405 | // some login 406 | } 407 | } 408 | ``` 409 | 410 | #### Build-in interceptor 411 | 412 | ```js 413 | import { UseInterceptors, ClassSerializerInterceptor } from 'egg-pig'; 414 | 415 | class RoleEntity { 416 | id: number; 417 | name: string; 418 | constructor(partial: Partial) { 419 | Object.assign(this, partial); 420 | } 421 | } 422 | 423 | class UserEntity { 424 | id: number; 425 | firstName: string; 426 | lastName: string; 427 | 428 | @Exclude() 429 | password: string; 430 | 431 | @Expose() 432 | get fullName() { 433 | return `${this.firstName} ${this.lastName}` 434 | } 435 | @Transform(role => role.name) 436 | role: RoleEntity 437 | 438 | constructor(partial: Partial) { 439 | Object.assign(this, partial); 440 | } 441 | } 442 | 443 | 444 | @Controller('serializer') 445 | @UseInterceptors(new ClassSerializerInterceptor()) 446 | export class SerializerController { 447 | 448 | @Get() 449 | async foo() { 450 | return [new UserEntity({ 451 | id: 1, 452 | firstName: 'jay', 453 | lastName: 'chou', 454 | password: '123456', 455 | role: new RoleEntity({ id: 1, name: 'admin' }) 456 | }), new UserEntity({ 457 | id: 2, 458 | firstName: 'kamic', 459 | lastName: 'xxxla', 460 | password: '45678', 461 | role: new RoleEntity({ id: 2, name: 'user01' }) 462 | })] 463 | } 464 | } 465 | ``` 466 | 467 | ### filter 468 | 469 | ```js 470 | 471 | import { Controller, Get } from 'egg-pig'; 472 | 473 | 474 | @Controller('cats') 475 | export class CatsController { 476 | 477 | @Get() 478 | async foo(){ 479 | throw new Error('some ..') 480 | } 481 | } 482 | ``` 483 | When the client calls this endpoint,the eggjs will hanlde. 484 | 485 | ```js 486 | import { 487 | Controller, 488 | Get, 489 | HttpException, 490 | HttpStatus, 491 | } from 'egg-pig'; 492 | 493 | @Controller('cats') 494 | export class CatsController { 495 | @Get() 496 | async foo(){ 497 | throw new HttpException('Forbidden', HttpStatus.FORBIDDEN); 498 | } 499 | } 500 | ``` 501 | When the client calls this endpoint, the response would look like this: 502 | ```json 503 | { 504 | "statusCode": 403, 505 | "message": "Forbidden" 506 | } 507 | ``` 508 | 509 | another way 510 | 511 | ```js 512 | async foo(){ 513 | throw new HttpException({ 514 | status: HttpStatus.FORBIDDEN, 515 | error: 'This is a custom message', 516 | }, 403); 517 | } 518 | ``` 519 | 520 | ```js 521 | class ForbiddenException extends HttpException { 522 | constructor() { 523 | super('Forbidden', HttpStatus.FORBIDDEN); 524 | } 525 | } 526 | 527 | async foo(){ 528 | throw new ForbiddenException() 529 | } 530 | ``` 531 | 532 | **UseFilters** 533 | 534 | ```js 535 | import { Controller, Get, HttpException, HttpStatus, ExceptionFilter, UseFilters, Catch } from 'egg-pig'; 536 | 537 | @Catch(HttpException) 538 | class HttpExceptionFilter extends ExceptionFilter { 539 | catch(exception) { 540 | this.ctx.status = HttpStatus.FORBIDDEN; 541 | this.ctx.body = { 542 | statusCode: exception.getStatus(), 543 | timestamp: new Date().toISOString(), 544 | path: ctx.req.url 545 | } 546 | } 547 | } 548 | 549 | class ForbiddenException extends HttpException { 550 | constructor() { 551 | super('Forbidden', HttpStatus.FORBIDDEN); 552 | } 553 | } 554 | 555 | 556 | @Controller('cats') 557 | @UseFilters(HttpExceptionFilter) 558 | export class CatsController { 559 | @Get() 560 | async foo(){ 561 | throw new ForbiddenException(); 562 | } 563 | } 564 | ``` 565 | 566 | ### tips 567 | CanActivate, EgggInterceptor, PipeTransform, ExceptionFilter are all abstract class which extends `egg/BaseContextClass`, it means you can use this on methods . such as 568 | 569 | ```js 570 | class XXPipe extends PipeTransform{ 571 | async transform(value, metadata){ 572 | await this.service.foo.bar(); 573 | console.log(this.config) 574 | this.foo(); 575 | return value; 576 | } 577 | foo(){ 578 | // logic 579 | } 580 | } 581 | ``` 582 | 583 | ### global 584 | 585 | global prefix/guards/pipes/interceptors/filters 586 | 587 | ```js 588 | // config.defalut.js 589 | export default (appInfo: EggAppConfig) => { 590 | 591 | config.globalPrefix = '/api/v1'; 592 | 593 | config.globalGuards = [new FooGuard(), FooGuard]; 594 | 595 | config.globalPipes = [new FooPipe(), FooPipe]; 596 | 597 | config.globalInterceptors = [new FooIn(), FooIn]; 598 | 599 | config.globalFilters = [new FooFilter(), FooFilter] 600 | 601 | return config; 602 | }; 603 | 604 | ``` 605 | 606 | ### Custom Decorators 607 | 608 | ```js 609 | import { BaseContextClass } from 'egg'; 610 | import { Controller, Get, PipeTransform, Pipe, createParamDecorator } from 'egg-pig'; 611 | 612 | const User = createParamDecorator((data, ctx) => { 613 | // data = 'test' => @User('test') 614 | return ctx.user; 615 | }); 616 | 617 | @Pipe() 618 | class APipe extends PipeTransform { 619 | transform(val, metadata) { 620 | // val => ctx.user; 621 | val && metadata; 622 | return val; 623 | } 624 | } 625 | 626 | 627 | @Controller('user') 628 | export class HomeController { 629 | @Get() 630 | public async index(@User('test', APipe) user){ 631 | return user; 632 | } 633 | } 634 | 635 | ``` 636 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { EggLoader } = require('egg-core'); 4 | 5 | module.exports = () => { 6 | 7 | const defaultLoadController = EggLoader.prototype.loadController; 8 | 9 | EggLoader.prototype.loadController = function() { 10 | 11 | defaultLoadController.call(this); 12 | 13 | if (this.config.eggpig.pig) { 14 | 15 | // extends 16 | this.createMethodsProxy(); 17 | } 18 | 19 | }; 20 | 21 | Object.assign(EggLoader.prototype, require('./lib/loader/egg_loader')); 22 | 23 | }; 24 | -------------------------------------------------------------------------------- /app/extend/helper.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const DecoratorManager = require('../../lib/decorator_manager'); 3 | const REFLECTOR = Symbol('helper#reflector'); 4 | 5 | module.exports = { 6 | get reflector() { 7 | if (!this[REFLECTOR]) { 8 | this[REFLECTOR] = { 9 | get(metadataKey, target) { 10 | return DecoratorManager.getMetadata(metadataKey, target); 11 | }, 12 | }; 13 | } 14 | return this[REFLECTOR]; 15 | }, 16 | }; 17 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - nodejs_version: '8' 4 | - nodejs_version: '10' 5 | - nodejs_version: '12' 6 | 7 | install: 8 | - ps: Install-Product node $env:nodejs_version 9 | - npm i npminstall && node_modules\.bin\npminstall 10 | 11 | test_script: 12 | - node --version 13 | - npm --version 14 | - npm run test 15 | 16 | build: off 17 | -------------------------------------------------------------------------------- /config/config.default.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | exports.eggpig = { 4 | pig: true, 5 | app: true, 6 | agent: false, 7 | loadController: true, 8 | }; 9 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import { BaseContextClass, Router } from 'egg'; 2 | import { Observable } from 'rxjs'; 3 | 4 | 5 | export enum HttpStatus { 6 | CONTINUE = 100, 7 | SWITCHING_PROTOCOLS = 101, 8 | PROCESSING = 102, 9 | OK = 200, 10 | CREATED = 201, 11 | ACCEPTED = 202, 12 | NON_AUTHORITATIVE_INFORMATION = 203, 13 | NO_CONTENT = 204, 14 | RESET_CONTENT = 205, 15 | PARTIAL_CONTENT = 206, 16 | AMBIGUOUS = 300, 17 | MOVED_PERMANENTLY = 301, 18 | FOUND = 302, 19 | SEE_OTHER = 303, 20 | NOT_MODIFIED = 304, 21 | TEMPORARY_REDIRECT = 307, 22 | PERMANENT_REDIRECT = 308, 23 | BAD_REQUEST = 400, 24 | UNAUTHORIZED = 401, 25 | PAYMENT_REQUIRED = 402, 26 | FORBIDDEN = 403, 27 | NOT_FOUND = 404, 28 | METHOD_NOT_ALLOWED = 405, 29 | NOT_ACCEPTABLE = 406, 30 | PROXY_AUTHENTICATION_REQUIRED = 407, 31 | REQUEST_TIMEOUT = 408, 32 | CONFLICT = 409, 33 | GONE = 410, 34 | LENGTH_REQUIRED = 411, 35 | PRECONDITION_FAILED = 412, 36 | PAYLOAD_TOO_LARGE = 413, 37 | URI_TOO_LONG = 414, 38 | UNSUPPORTED_MEDIA_TYPE = 415, 39 | REQUESTED_RANGE_NOT_SATISFIABLE = 416, 40 | EXPECTATION_FAILED = 417, 41 | I_AM_A_TEAPOT = 418, 42 | UNPROCESSABLE_ENTITY = 422, 43 | TOO_MANY_REQUESTS = 429, 44 | INTERNAL_SERVER_ERROR = 500, 45 | NOT_IMPLEMENTED = 501, 46 | BAD_GATEWAY = 502, 47 | SERVICE_UNAVAILABLE = 503, 48 | GATEWAY_TIMEOUT = 504, 49 | HTTP_VERSION_NOT_SUPPORTED = 505, 50 | } 51 | 52 | export enum RequestMethod { 53 | GET = '0', 54 | POST = '1', 55 | PUT = '2', 56 | DELETE = '3', 57 | PATCH = '4', 58 | ALL = '5', 59 | OPTIONS = '6', 60 | HEAD = '7', 61 | } 62 | 63 | 64 | 65 | type ParamData = object | string | number; 66 | 67 | type Paramtype = 'BODY' | 'QUERY' | 'PARAM' | 'CUSTOM'; 68 | 69 | interface GetFileStreamOptions { 70 | requireFile?: boolean; // required file submit, default is true 71 | defCharset?: string; 72 | limits?: { 73 | fieldNameSize?: number; 74 | fieldSize?: number; 75 | fields?: number; 76 | fileSize?: number; 77 | files?: number; 78 | parts?: number; 79 | headerPairs?: number; 80 | }; 81 | checkFile?( 82 | fieldname: string, 83 | file: any, 84 | filename: string, 85 | encoding: string, 86 | mimetype: string 87 | ): void | Error; 88 | } 89 | 90 | interface GetFilesStreamOptions extends GetFileStreamOptions { 91 | autoFields?: boolean; 92 | } 93 | 94 | interface ParamRouterOptions { 95 | routerName?: string; 96 | middleware?: (string | Function)[], 97 | } 98 | 99 | 100 | export function Injectable(): any; 101 | 102 | export function Request(): (target, key, index: number) => any; 103 | export function Response(): (target, key, index: number) => any; 104 | export function Req(): (target, key, index: number) => any; 105 | export function Res(): (target, key, index: number) => any; 106 | export function Headers(property?: string): (target, key, index: number) => any; 107 | export function Session(): (target, key, index: number) => any; 108 | export function UploadedFile(): (target, key, index: number) => any; 109 | export function UploadedFiles(): (target, key, index: number) => any; 110 | export function UploadedFileStream(opts?: GetFileStreamOptions): (target, key, index: number) => any; 111 | export function UploadedFilesStream(opts?: GetFilesStreamOptions): (target, key, index: number) => any; 112 | 113 | export function Param(): (target, key, index: number) => any; 114 | export function Param(...pipes: (Type | PipeTransform)[]): (target, key, index: number) => any; 115 | export function Param(property: string, ...pipes: (Type | PipeTransform)[]): (target, key, index: number) => any; 116 | 117 | export function Query(): (target, key, index: number) => any; 118 | export function Query(...pipes: (Type | PipeTransform)[]): (target, key, index: number) => any; 119 | export function Query(property: string, ...pipes: (Type | PipeTransform)[]): (target, key, index: number) => any; 120 | 121 | export function Body(): (target, key, index: number) => any; 122 | export function Body(...pipes: (Type | PipeTransform)[]): (target, key, index: number) => any; 123 | export function Body(property: string, ...pipes: (Type | PipeTransform)[]): (target, key, index: number) => any; 124 | 125 | 126 | 127 | export function Head(path?: string, routerOptions?: ParamRouterOptions): (target, key, descriptor: PropertyDescriptor) => any; 128 | export function Get(path?: string, routerOptions?: ParamRouterOptions): (target, key, descriptor: PropertyDescriptor) => any; 129 | export function All(path?: string, routerOptions?: ParamRouterOptions): (target, key, descriptor: PropertyDescriptor) => any; 130 | export function Post(path?: string, routerOptions?: ParamRouterOptions): (target, key, descriptor: PropertyDescriptor) => any; 131 | export function Delete(path?: string, routerOptions?: ParamRouterOptions): (target, key, descriptor: PropertyDescriptor) => any; 132 | export function Options(path?: string, routerOptions?: ParamRouterOptions): (target, key, descriptor: PropertyDescriptor) => any; 133 | export function Put(path?: string, routerOptions?: ParamRouterOptions): (target, key, descriptor: PropertyDescriptor) => any; 134 | export function Patch(path?: string, routerOptions?: ParamRouterOptions): (target, key, descriptor: PropertyDescriptor) => any; 135 | 136 | export function Render(template: string): (target, key, descriptor: PropertyDescriptor) => any; 137 | export function Header(name: string, value: string): (target, key, descriptor: PropertyDescriptor) => any; 138 | export function Header(obj: object): (target, key, descriptor: PropertyDescriptor) => any; 139 | export function HttpCode(statusCode: number): (target, key, descriptor: PropertyDescriptor) => any; 140 | 141 | export function UsePipes(...pipes: (PipeTransform | Function)[]): any; 142 | export function UseGuards(...guards: (CanActivate | Function)[]): any; 143 | export function UseInterceptors(...interceptors: (EggInterceptor | Function)[]): any; 144 | export function UseFilters(...filters: (ExceptionFilter | Function)[]): any; 145 | 146 | export function Controller(path?: string, routerOptions?: { sensitive?: boolean; middleware?: (string | Function)[]; }): (target: object) => any; 147 | 148 | export function Resources(name: string, options?: { name?: string; middleware?: (string | Function)[], }): (target: object) => any; 149 | export function Restful(name: string, options?: { name?: string; middleware?: (string | Function)[], }): (target: object) => any; 150 | 151 | export function Priority(priority?: number): (target: object) => any 152 | 153 | interface ArgumentMetadata { 154 | readonly type: Paramtype; 155 | readonly metatype?: new (...args) => any | undefined; 156 | readonly data?: string | undefined; 157 | } 158 | 159 | interface Type extends Function { 160 | new(...args: any[]): T; 161 | } 162 | 163 | // interface RouteInfo { 164 | // readonly path: string; 165 | // readonly method: RequestMethod; 166 | // } 167 | 168 | interface ExecutionContext { 169 | getClass(): Type; // use for class 170 | getHandler(): Function; // classMethod 171 | } 172 | 173 | // interface IMiddleware { 174 | // apply(...middleware: (Function | any)[]): this; 175 | // forRoutes(...routes: (string | RouteInfo | object)[]): this; 176 | // exclude(...routes: Array): this; 177 | // } 178 | 179 | export abstract class CanActivate extends BaseContextClass { 180 | constructor(...args: any[]); 181 | abstract canActivate(context: ExecutionContext): boolean | Promise | Observable; 182 | } 183 | 184 | 185 | export interface CallHandler { 186 | handle(): Observable; 187 | } 188 | 189 | export abstract class EggInterceptor extends BaseContextClass { 190 | constructor(...args: any[]); 191 | abstract intercept( 192 | context: ExecutionContext, 193 | call$: CallHandler, 194 | ): Observable | Promise>; 195 | } 196 | 197 | export abstract class PipeTransform extends BaseContextClass { 198 | constructor(...args: any[]); 199 | abstract transform(value: T, metadata: ArgumentMetadata): R; 200 | } 201 | 202 | export abstract class ExceptionFilter extends BaseContextClass { 203 | constructor(...args: any[]); 204 | abstract catch(exception: T): any; 205 | } 206 | 207 | export function Catch(...exceptions: Type[]): any; 208 | 209 | export function createParamDecorator(factory: (data, req) => any): (data?: any, ...pipes) => any; 210 | 211 | 212 | // export class MiddlewareConsumer { 213 | // static setRouter(router: Router): IMiddleware; 214 | // static apply(...middleware: (Function | any)[]): IMiddleware; 215 | // } 216 | 217 | export function ReflectMetadata(metadataKey, metadataValue): (target, key?, descriptor?) => any; 218 | 219 | export class HttpException extends Error { 220 | 221 | readonly message: any; 222 | 223 | constructor(response: string | object, status: number); 224 | 225 | getResponse(): string | object; 226 | 227 | getStatus(): number; 228 | } 229 | 230 | export class ForbiddenException extends HttpException { 231 | constructor(message?: string | object | any, error = 'Forbidden'); 232 | } 233 | 234 | export class BadRequestException extends HttpException { 235 | constructor(message?: string | object | any, error = 'Bad Request'); 236 | } 237 | 238 | export class UnauthorizedException extends HttpException { 239 | constructor(message?: string | object | any, error = 'Unauthorized'); 240 | } 241 | 242 | export class NotFoundException extends HttpException { 243 | constructor(message?: string | object | any, error = 'Not Found'); 244 | } 245 | 246 | export class NotAcceptableException extends HttpException { 247 | constructor(message?: string | object | any, error = 'Not Acceptable'); 248 | } 249 | export class RequestTimeoutException extends HttpException { 250 | constructor(message?: string | object | any, error = 'Request Timeout'); 251 | } 252 | 253 | export class ConflictException extends HttpException { 254 | constructor(message?: string | object | any, error = 'Conflict'); 255 | } 256 | export class GoneException extends HttpException { 257 | constructor(message?: string | object | any, error = 'Gone'); 258 | } 259 | export class PayloadTooLargeException extends HttpException { 260 | constructor(message?: string | object | any, error = 'Payload Too Large'); 261 | } 262 | 263 | export class UnsupportedMediaTypeException extends HttpException { 264 | constructor(message?: string | object | any, error = 'Unsupported Media Type'); 265 | } 266 | 267 | export class UnprocessableEntityException extends HttpException { 268 | constructor(message?: string | object | any, error = 'Unprocessable Entity'); 269 | } 270 | export class InternalServerErrorException extends HttpException { 271 | constructor(message?: string | object | any, error = 'Internal Server Error'); 272 | } 273 | 274 | export class NotImplementedException extends HttpException { 275 | constructor(message?: string | object | any, error = 'Not Implemented'); 276 | } 277 | 278 | export class BadGatewayException extends HttpException { 279 | constructor(message?: string | object | any, error = 'Bad Gateway'); 280 | } 281 | 282 | export class ServiceUnavailableException extends HttpException { 283 | constructor(message?: string | object | any, error = 'Service Unavailable'); 284 | } 285 | 286 | export class GatewayTimeoutException extends HttpException { 287 | constructor(message?: string | object | any, error = 'Gateway Timeout'); 288 | } 289 | 290 | interface ValidatorOptions { 291 | skipMissingProperties?: boolean; 292 | whitelist?: boolean; 293 | forbidNonWhitelisted?: boolean; 294 | groups?: string[]; 295 | dismissDefaultMessages?: boolean; 296 | validationError?: { 297 | target?: boolean; 298 | value?: boolean; 299 | }; 300 | forbidUnknownValues?: boolean; 301 | } 302 | 303 | interface ValidationPipeOptions extends ValidatorOptions { 304 | transform?: boolean; 305 | disableErrorMessages?: boolean; 306 | } 307 | 308 | 309 | export class ParseIntPipe extends PipeTransform { 310 | transform(value: string, metadata: ArgumentMetadata): any; 311 | } 312 | 313 | export class ValidationPipe extends PipeTransform { 314 | constructor(options?: ValidationPipeOptions); 315 | transform(value, metadata: ArgumentMetadata); 316 | } 317 | 318 | export class ClassSerializerInterceptor extends EggInterceptor { 319 | intercept(context: ExecutionContext, call$: Observable): Observable; 320 | } 321 | 322 | export abstract class RestController extends BaseContextClass { 323 | // get /posts/new 324 | new(...params: any[]): Promise; 325 | // get /posts 326 | index(...params: any[]): Promise; 327 | // get /posts/:id 328 | show(...params: any[]): Promise; 329 | // get /posts/:id/edit 330 | edit(...params: any[]): Promise; 331 | // post /posts 332 | create(...params: any[]): Promise; 333 | // patch /posts/:id 334 | update(...params: any[]): Promise; 335 | // delete /posts/:id 336 | destroy(...params: any[]): Promise 337 | } 338 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const common = require('./lib/common'); 3 | const constant = require('./lib/constants'); 4 | const decorator = require('./lib/decorator'); 5 | const HttpStatus = require('./lib/exceptions/constant'); 6 | const HttpException = require('./lib/exceptions/exception'); 7 | 8 | module.exports = { 9 | ...common, 10 | ...constant, 11 | ...decorator, 12 | ...HttpStatus, 13 | ...HttpException, 14 | CanActivate: class { }, 15 | PipeTransform: class { }, 16 | EggInterceptor: class { }, 17 | ExceptionFilter: class { }, 18 | }; 19 | 20 | -------------------------------------------------------------------------------- /lib/common/class-serializer.interceptor.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | require('reflect-metadata'); 4 | const is = require('is-type-of'); 5 | const { loadPackage } = require('../utils'); 6 | const { map } = require('rxjs/operators'); 7 | 8 | const DecoratorManager = require('../decorator_manager'); 9 | 10 | const CLASS_SERIALIZER_OPTIONS = 'class_serializer:options'; 11 | 12 | let classTransformer = {}; 13 | 14 | module.exports = class ClassSerializerInterceptor { 15 | 16 | constructor() { 17 | const loadPkg = pkg => loadPackage(pkg, 'ClassSerializerInterceptor'); 18 | classTransformer = loadPkg('class-transformer'); 19 | } 20 | 21 | intercept(context, call$) { 22 | const options = this.getContextOptions(context); 23 | return call$.handle().pipe( 24 | map(res => this.serialize(res, options)) 25 | ); 26 | } 27 | 28 | serialize(response, options) { 29 | const isArray = Array.isArray(response); 30 | if (!is.object(response) && !isArray) { 31 | return response; 32 | } 33 | return isArray 34 | ? response.map(item => this.transformPlain(item, options)) 35 | : this.transformPlain(response, options); 36 | } 37 | 38 | transformPlain(plainOrClass, options) { 39 | return plainOrClass && plainOrClass.constructor !== Object 40 | ? classTransformer.classToPlain(plainOrClass, options) 41 | : plainOrClass; 42 | } 43 | 44 | getContextOptions(context) { 45 | return ( 46 | DecoratorManager.getMetadata(CLASS_SERIALIZER_OPTIONS, context.getHandler()) || 47 | DecoratorManager.getMetadata(CLASS_SERIALIZER_OPTIONS, context.getClass()) 48 | ); 49 | } 50 | 51 | }; 52 | 53 | -------------------------------------------------------------------------------- /lib/common/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | exports.ParseIntPipe = require('./parse-int.pipe'); 3 | exports.ValidationPipe = require('./validation.pipe'); 4 | exports.ClassSerializerInterceptor = require('./class-serializer.interceptor'); 5 | -------------------------------------------------------------------------------- /lib/common/parse-int.pipe.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const { BadRequestException } = require('../exceptions/exception'); 3 | 4 | module.exports = class ParseIntPipe { 5 | async transform(value) { 6 | const isNumeric = 7 | typeof value === 'string' && 8 | !isNaN(parseFloat(value)) && 9 | isFinite(value); 10 | if (!isNumeric) { 11 | throw new BadRequestException( 12 | 'Validation failed (numeric string is expected)' 13 | ); 14 | } 15 | return parseInt(value, 10); 16 | } 17 | }; 18 | 19 | -------------------------------------------------------------------------------- /lib/common/validation.pipe.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const is = require('is-type-of'); 3 | const { loadPackage } = require('../utils'); 4 | const { BadRequestException } = require('../exceptions/exception'); 5 | 6 | let classValidator = {}; 7 | let classTransformer = {}; 8 | 9 | module.exports = class ValidationPipe { 10 | 11 | constructor(options = {}) { 12 | const { transform, disableErrorMessages, ...validatorOptions } = options; 13 | const loadPkg = pkg => loadPackage(pkg, 'ValidationPipe'); 14 | this.isTransformEnabled = !!transform; 15 | this.validatorOptions = validatorOptions; 16 | this.isDetailedOutputDisabled = disableErrorMessages; 17 | classValidator = loadPkg('class-validator'); 18 | classTransformer = loadPkg('class-transformer'); 19 | } 20 | 21 | async transform(value, metadata) { 22 | const { metatype } = metadata; 23 | if (!metatype || !this.toValidate(metadata)) { 24 | return value; 25 | } 26 | const entity = classTransformer.plainToClass( 27 | metatype, 28 | this.toEmptyIfNil(value) 29 | ); 30 | const errors = await classValidator.validate(entity, this.validatorOptions); 31 | if (errors.length > 0) { 32 | throw new BadRequestException( 33 | this.isDetailedOutputDisabled ? undefined : errors 34 | ); 35 | } 36 | return this.isTransformEnabled 37 | ? entity 38 | : Object.keys(this.validatorOptions).length > 0 39 | ? classTransformer.classToPlain(entity) 40 | : value; 41 | } 42 | 43 | toValidate(metadata) { 44 | const { metatype, type } = metadata; 45 | if (type.toLowerCase() === 'custom') { 46 | return false; 47 | } 48 | const types = [ String, Boolean, Number, Array, Object ]; 49 | return !types.some(t => metatype === t) && !is.null(metatype); 50 | } 51 | 52 | toEmptyIfNil(value) { 53 | return is.null(value) ? {} : value; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /lib/constants.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | exports.RouteParamTypes = { 3 | QUERY: '0', 4 | 0: 'QUERY', 5 | BODY: '1', 6 | 1: 'BODY', 7 | PARAM: '2', 8 | 2: 'PARAM', 9 | CONTEXT: '3', 10 | 3: 'CONTEXT', 11 | REQUEST: '4', 12 | 4: 'REQUEST', 13 | RESPONSE: '5', 14 | 5: 'RESPONSE', 15 | HEADERS: '6', 16 | 6: 'HEADERS', 17 | SESSION: '7', 18 | 7: 'SESSION', 19 | FILE: '8', 20 | 8: 'FILE', 21 | FILES: '9', 22 | 9: 'FILES', 23 | FILESTREAM: '10', 24 | 10: 'FILESTREAM', 25 | FILESSTREAM: '11', 26 | 11: 'FILESSTREAM', 27 | CUSTOM: '10', 28 | 12: 'CUSTOM', 29 | }; 30 | 31 | 32 | exports.RequestMethod = { 33 | GET: 'get', 34 | POST: 'post', 35 | PUT: 'put', 36 | DELETE: 'delete', 37 | PATCH: 'patch', 38 | ALL: 'all', 39 | OPTIONS: 'options', 40 | HEAD: 'head', 41 | }; 42 | 43 | // egg router 44 | exports.REST_MAP = { 45 | index: { 46 | suffix: '', 47 | method: 'GET', 48 | }, 49 | new: { 50 | namePrefix: 'new_', 51 | member: true, 52 | suffix: 'new', 53 | method: 'GET', 54 | }, 55 | create: { 56 | suffix: '', 57 | method: 'POST', 58 | }, 59 | show: { 60 | member: true, 61 | suffix: ':id', 62 | method: 'GET', 63 | }, 64 | edit: { 65 | member: true, 66 | namePrefix: 'edit_', 67 | suffix: ':id/edit', 68 | method: 'GET', 69 | }, 70 | update: { 71 | member: true, 72 | namePrefix: '', 73 | suffix: ':id', 74 | method: [ 'PATCH', 'PUT' ], 75 | }, 76 | destroy: { 77 | member: true, 78 | namePrefix: 'destroy_', 79 | suffix: ':id', 80 | method: 'DELETE', 81 | }, 82 | }; 83 | 84 | 85 | exports.PATH_METADATA = '__pathMetadata__'; 86 | exports.METHOD_METADATA = '__methodMetadata__'; 87 | exports.PRIORITY_METADATA = '__priorityMetadata__'; 88 | // exports.ROUTE_NAME_METADATA = '__routeNameMetadata__'; 89 | exports.ROUTE_OPTIONS_METADATA = '__routeOptionMetadata__'; 90 | exports.CONTROLLER_MODULE_METADATA = '__controllerModuleMetadata__'; 91 | 92 | exports.GUARDS_METADATA = '__guardsMetadata__'; 93 | exports.PIPES_METADATA = '__pipesMetadata__'; 94 | exports.INTERCEPTORS_METADATA = '__interceptorMetadata__'; 95 | exports.EXCEPTION_FILTERS_METADATA = '__exceptionFilters__'; 96 | exports.FILTER_CATCH_EXCEPTIONS = '__filterCatchExceptions__'; 97 | 98 | exports.ROUTE_ARGS_METADATA = '__routeArgsMetadata__'; 99 | exports.RENDER_METADATA = '__renderMetadata__'; 100 | exports.HEADER_METADATA = '__headerMetadata__'; 101 | exports.HTTP_CODE_METADATA = '__httpCode__'; 102 | exports.PARAMTYPES_METADATA = 'design:paramtypes'; 103 | exports.SELF_DECLARED_DEPS_METADATA = 'self:paramtypes'; 104 | -------------------------------------------------------------------------------- /lib/decorator.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const is = require('is-type-of'); 3 | const DecoratorManager = require('./decorator_manager'); 4 | const uuid = require('uuid').v4; 5 | const { 6 | RouteParamTypes, 7 | RequestMethod, 8 | GUARDS_METADATA, 9 | INTERCEPTORS_METADATA, 10 | EXCEPTION_FILTERS_METADATA, 11 | FILTER_CATCH_EXCEPTIONS, 12 | HTTP_CODE_METADATA, 13 | PIPES_METADATA, 14 | ROUTE_ARGS_METADATA, 15 | PATH_METADATA, 16 | ROUTE_OPTIONS_METADATA, 17 | RENDER_METADATA, 18 | HEADER_METADATA, 19 | PRIORITY_METADATA, 20 | CONTROLLER_MODULE_METADATA, 21 | } = require('./constants'); 22 | 23 | 24 | // function randomString() { 25 | // return Math.random() 26 | // .toString(36) 27 | // .substring(2, 15); 28 | // } 29 | 30 | function validatePath(path) { 31 | return path.charAt(0) !== '/' ? '/' + path : path; 32 | } 33 | 34 | function validateRouteName(name) { 35 | return name.charAt(0) === '/' ? name.substring(1) : name; 36 | } 37 | 38 | 39 | const validPipe = pipe => pipe && (is.function(pipe) || is.function(pipe.transform)); 40 | const validGuard = guard => guard && (is.function(guard) || is.function(guard.canActivate)); 41 | const validFilter = filter => filter && (is.function(filter) || is.function(filter.catch)); 42 | const validInterceptor = interceptor => interceptor && (is.function(interceptor) || is.function(interceptor.intercept)); 43 | 44 | /** 45 | * @param {Array} arr : xxxGuard 46 | * @param {Function} validataFn : validGuard, validPipe 47 | * @param {Function|Object} klass : classMethod or klass 48 | * @param {String} descriptor : '@UseGuard' 49 | * @param {String} item : 'guard' 50 | */ 51 | function validEach(arr, validataFn, klass, descriptor, item) { 52 | const flags = arr.filter(a => { 53 | return !validataFn(a); 54 | }); 55 | if (flags.length > 0) { 56 | throw new Error(`Invalid ${item} passed to ${descriptor}() decorator ${klass.name}`); 57 | } 58 | } 59 | 60 | function validEachFactory(metadata, arr, classOrClassMethod) { 61 | if (metadata === GUARDS_METADATA) { 62 | validEach(arr, validGuard, classOrClassMethod, '@UseGuards', 'guard'); 63 | return; 64 | } 65 | 66 | if (metadata === PIPES_METADATA) { 67 | validEach(arr, validPipe, classOrClassMethod, '@UsePipes', 'pipe'); 68 | return; 69 | } 70 | 71 | if (metadata === INTERCEPTORS_METADATA) { 72 | validEach(arr, validInterceptor, classOrClassMethod, '@UseInterceptors', 'interceptor'); 73 | return; 74 | } 75 | 76 | if (metadata === EXCEPTION_FILTERS_METADATA) { 77 | validEach(arr, validFilter, classOrClassMethod, '@UseFilters', 'filter'); 78 | return; 79 | } 80 | } 81 | 82 | function createParamMapping(paramType, factory) { 83 | return (data, ...pipes) => { 84 | return (target, key, index) => { 85 | const isFile = paramType === RouteParamTypes.FILE 86 | || paramType === RouteParamTypes.FILES 87 | || paramType === RouteParamTypes.FILESTREAM 88 | || paramType === RouteParamTypes.FILESSTREAM; 89 | const hasParamData = is.nullOrUndefined(data) || is.string(data); 90 | const paramData = (hasParamData || isFile) ? data : undefined; 91 | const paramPipe = (hasParamData || isFile) ? pipes : [ data, ...pipes ]; 92 | const args = DecoratorManager.getMethodDataFromClass(ROUTE_ARGS_METADATA, target, key) || {}; 93 | DecoratorManager.saveMethodDataToClass(ROUTE_ARGS_METADATA, { 94 | ...args, 95 | [`${paramType}:${index}`]: { 96 | index, 97 | factory, 98 | data: paramData, 99 | pipes: paramPipe, 100 | }, 101 | }, target, key); 102 | }; 103 | }; 104 | } 105 | 106 | // 107 | function createRouterMapping(methodType = RequestMethod.GET) { 108 | return (name, paramOptions) => { 109 | return (target, key, descriptor) => { 110 | const options = {}; 111 | 112 | // get('/user') 113 | if (name && !paramOptions) { 114 | options.path = validatePath(name); 115 | } 116 | // get() 117 | if (!name) { 118 | options.path = '/'; 119 | } 120 | // get('/user', {routerName:'', middlewaer:[]}) 121 | if (name && paramOptions) { 122 | options.path = validatePath(name); 123 | options.paramOptions = paramOptions; 124 | } 125 | 126 | options.requestMethod = methodType; 127 | options.method = key; 128 | options.targetCallback = target[key]; 129 | 130 | DecoratorManager.attachClassMetadata(ROUTE_OPTIONS_METADATA, options, target); 131 | 132 | return descriptor; 133 | }; 134 | }; 135 | } 136 | 137 | 138 | function createUseMapping(metadata) { 139 | return (...arr) => (target, key, descriptor) => { 140 | if (descriptor) { 141 | validEachFactory(metadata, arr, descriptor.value); 142 | DecoratorManager.saveMethodDataToClass(metadata, arr, target, key); 143 | return descriptor; 144 | } 145 | validEachFactory(metadata, arr, target); 146 | DecoratorManager.saveClassMetadata(metadata, arr, target); 147 | return target; 148 | }; 149 | } 150 | 151 | // filter catch 152 | exports.Catch = function Catch(...exceptions) { 153 | return target => { 154 | DecoratorManager.saveClassMetadata(FILTER_CATCH_EXCEPTIONS, exceptions, target); 155 | }; 156 | }; 157 | 158 | // controller 159 | // routerOptions = { 160 | // sensitive: boolean; 161 | // middleware: KoaMiddlewareParamArray; 162 | // } 163 | exports.Controller = function Controller(prefix = '/', routerOptions = { middleware: [], sensitive: true }) { 164 | return target => { 165 | DecoratorManager.saveModule(CONTROLLER_MODULE_METADATA, target); 166 | DecoratorManager.saveClassMetadata(PATH_METADATA, { 167 | name: '', 168 | prefix: validatePath(prefix), 169 | isRestful: false, 170 | routerOptions, 171 | }, target); 172 | }; 173 | }; 174 | 175 | // router priority 176 | exports.Priority = function Priority(priority = 0) { 177 | return target => { 178 | DecoratorManager.saveClassMetadata(PRIORITY_METADATA, priority, target); 179 | }; 180 | }; 181 | 182 | // resources 183 | exports.Resources = function Resources(prefix, routerOptions = { middleware: [], sensitive: true }) { 184 | return target => { 185 | DecoratorManager.saveModule(CONTROLLER_MODULE_METADATA, target); 186 | DecoratorManager.saveClassMetadata(PATH_METADATA, { 187 | name: validateRouteName(routerOptions.name || prefix), 188 | prefix: validatePath(prefix), 189 | isRestful: true, 190 | routerOptions, 191 | }, target); 192 | return target; 193 | }; 194 | }; 195 | 196 | // httpcode 197 | 198 | exports.HttpCode = function HttpCode(statusCode) { 199 | return (target, key) => { 200 | DecoratorManager.saveMethodDataToClass(HTTP_CODE_METADATA, statusCode, target, key); 201 | }; 202 | }; 203 | 204 | exports.Render = function Render(template) { 205 | return (target, key) => { 206 | DecoratorManager.saveMethodDataToClass(RENDER_METADATA, template, target, key); 207 | }; 208 | }; 209 | 210 | exports.Header = function Header(name, value) { 211 | return (target, key) => { 212 | DecoratorManager.attachMethodDataToClass(HEADER_METADATA, { name, value }, target, key); 213 | }; 214 | }; 215 | 216 | exports.createParamDecorator = function createParamDecorator(factory) { 217 | const paramtype = uuid(); 218 | return createParamMapping(paramtype, factory); 219 | }; 220 | 221 | exports.ReflectMetadata = function ReflectMetadata(metadataKey, metadataValue) { 222 | return (target, key, descriptor) => { 223 | if (descriptor) { 224 | DecoratorManager.defineMetadata(metadataKey, metadataValue, descriptor.value); 225 | return descriptor; 226 | } 227 | DecoratorManager.defineMetadata(metadataKey, metadataValue, target); 228 | return target; 229 | }; 230 | }; 231 | 232 | // paramtypes 233 | exports.Body = createParamMapping(RouteParamTypes.BODY); 234 | exports.Param = createParamMapping(RouteParamTypes.PARAM); 235 | exports.Query = createParamMapping(RouteParamTypes.QUERY); 236 | exports.Session = createParamMapping(RouteParamTypes.SESSION); 237 | exports.Headers = createParamMapping(RouteParamTypes.HEADERS); 238 | exports.Request = createParamMapping(RouteParamTypes.REQUEST); 239 | exports.Response = createParamMapping(RouteParamTypes.RESPONSE); 240 | exports.UploadedFile = createParamMapping(RouteParamTypes.FILE); 241 | exports.UploadedFiles = createParamMapping(RouteParamTypes.FILES); 242 | exports.UploadedFileStream = createParamMapping(RouteParamTypes.FILESTREAM); 243 | exports.UploadedFilesStream = createParamMapping(RouteParamTypes.FILESSTREAM); 244 | 245 | // http verb 246 | exports.Get = createRouterMapping(RequestMethod.GET); 247 | exports.All = createRouterMapping(RequestMethod.ALL); 248 | exports.Put = createRouterMapping(RequestMethod.PUT); 249 | exports.Post = createRouterMapping(RequestMethod.POST); 250 | exports.Head = createRouterMapping(RequestMethod.HEAD); 251 | exports.Patch = createRouterMapping(RequestMethod.PATCH); 252 | exports.Delete = createRouterMapping(RequestMethod.DELETE); 253 | exports.Options = createRouterMapping(RequestMethod.OPTIONS); 254 | 255 | // alias 256 | exports.Req = exports.Request; 257 | exports.Res = exports.Response; 258 | exports.Restful = exports.Resources; 259 | 260 | 261 | exports.UsePipes = createUseMapping(PIPES_METADATA); 262 | exports.UseGuards = createUseMapping(GUARDS_METADATA); 263 | exports.UseFilters = createUseMapping(EXCEPTION_FILTERS_METADATA); 264 | exports.UseInterceptors = createUseMapping(INTERCEPTORS_METADATA); 265 | 266 | // pipe/guard/interceptor/filters 267 | exports.Injectable = () => () => { }; 268 | -------------------------------------------------------------------------------- /lib/decorator_manager.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | require('reflect-metadata'); 3 | 4 | const { PARAMTYPES_METADATA } = require('./constants'); 5 | 6 | class DecoratorManager extends Map { 7 | 8 | 9 | constructor() { 10 | super(); 11 | /** 12 | * the key for meta data store in class 13 | */ 14 | this.injectClassKeyPrefix = 'INJECTION_CLASS_META_DATA'; 15 | /** 16 | * the key for method meta data store in class 17 | */ 18 | this.injectClassMethodKeyPrefix = 'INJECTION_CLASS_METHOD_META_DATA'; 19 | 20 | /** 21 | * the key for method meta data store in method 22 | */ 23 | this.injectMethodKeyPrefix = 'INJECTION_METHOD_META_DATA'; 24 | } 25 | 26 | saveModule(key, module) { 27 | if (!this.has(key)) { 28 | this.set(key, new Set()); 29 | } 30 | this.get(key).add(module); 31 | } 32 | 33 | static getDecoratorClassKey(decoratorNameKey) { 34 | return decoratorNameKey.toString() + '_CLS'; 35 | } 36 | 37 | static getDecoratorMethodKey(decoratorNameKey) { 38 | return decoratorNameKey.toString() + '_METHOD'; 39 | } 40 | 41 | static getDecoratorClsMethodPrefix(decoratorNameKey) { 42 | return decoratorNameKey.toString() + '_CLS_METHOD'; 43 | } 44 | 45 | static getDecoratorClsMethodKey(decoratorNameKey, methodKey) { 46 | return DecoratorManager.getDecoratorClsMethodPrefix(decoratorNameKey) + ':' + methodKey.toString(); 47 | } 48 | 49 | listModule(key) { 50 | return Array.from(this.get(key) || {}); 51 | } 52 | 53 | static getOriginMetadata(metaKey, target, method) { 54 | if (method) { 55 | // for property 56 | if (!Reflect.hasMetadata(metaKey, target, method)) { 57 | Reflect.defineMetadata(metaKey, new Map(), target, method); 58 | } 59 | return Reflect.getMetadata(metaKey, target, method); 60 | } 61 | // filter Object.create(null) 62 | if (typeof target === 'object' && target.constructor) { 63 | target = target.constructor; 64 | } 65 | // for class 66 | if (!Reflect.hasMetadata(metaKey, target)) { 67 | Reflect.defineMetadata(metaKey, new Map(), target); 68 | } 69 | return Reflect.getMetadata(metaKey, target); 70 | 71 | } 72 | 73 | saveMetadata(decoratorNameKey, data, target, propertyName) { 74 | if (propertyName) { 75 | const originMap = DecoratorManager.getOriginMetadata(this.injectMethodKeyPrefix, target, propertyName); 76 | originMap.set(DecoratorManager.getDecoratorMethodKey(decoratorNameKey), data); 77 | } else { 78 | const originMap = DecoratorManager.getOriginMetadata(this.injectClassKeyPrefix, target); 79 | originMap.set(DecoratorManager.getDecoratorClassKey(decoratorNameKey), data); 80 | } 81 | } 82 | 83 | attachMetadata(decoratorNameKey, data, target, propertyName) { 84 | let originMap; 85 | let key; 86 | if (propertyName) { 87 | originMap = DecoratorManager.getOriginMetadata(this.injectMethodKeyPrefix, target, propertyName); 88 | key = DecoratorManager.getDecoratorMethodKey(decoratorNameKey); 89 | } else { 90 | originMap = DecoratorManager.getOriginMetadata(this.injectClassKeyPrefix, target); 91 | key = DecoratorManager.getDecoratorClassKey(decoratorNameKey); 92 | } 93 | if (!originMap.has(key)) { 94 | originMap.set(key, []); 95 | } 96 | originMap.get(key).push(data); 97 | } 98 | 99 | getMetadata(decoratorNameKey, target, propertyName) { 100 | if (propertyName) { 101 | const originMap = DecoratorManager.getOriginMetadata(this.injectMethodKeyPrefix, target, propertyName); 102 | return originMap.get(DecoratorManager.getDecoratorMethodKey(decoratorNameKey)); 103 | } 104 | const originMap = DecoratorManager.getOriginMetadata(this.injectClassKeyPrefix, target); 105 | return originMap.get(DecoratorManager.getDecoratorClassKey(decoratorNameKey)); 106 | 107 | } 108 | 109 | savePropertyDataToClass(decoratorNameKey, data, target, propertyName) { 110 | const originMap = DecoratorManager.getOriginMetadata(this.injectClassMethodKeyPrefix, target); 111 | originMap.set(DecoratorManager.getDecoratorClsMethodKey(decoratorNameKey, propertyName), data); 112 | } 113 | 114 | attachPropertyDataToClass(decoratorNameKey, data, target, propertyName) { 115 | const originMap = DecoratorManager.getOriginMetadata(this.injectClassMethodKeyPrefix, target); 116 | const key = DecoratorManager.getDecoratorClsMethodKey(decoratorNameKey, propertyName); 117 | if (!originMap.has(key)) { 118 | originMap.set(key, []); 119 | } 120 | originMap.get(key).push(data); 121 | } 122 | 123 | getPropertyDataFromClass(decoratorNameKey, target, propertyName) { 124 | const originMap = DecoratorManager.getOriginMetadata(this.injectClassMethodKeyPrefix, target); 125 | return originMap.get(DecoratorManager.getDecoratorClsMethodKey(decoratorNameKey, propertyName)); 126 | } 127 | 128 | listPropertyDataFromClass(decoratorNameKey, target) { 129 | const originMap = DecoratorManager.getOriginMetadata(this.injectClassMethodKeyPrefix, target); 130 | const res = []; 131 | for (const [ key, value ] of originMap) { 132 | if (key.indexOf(DecoratorManager.getDecoratorClsMethodPrefix(decoratorNameKey)) !== -1) { 133 | res.push(value); 134 | } 135 | } 136 | return res; 137 | } 138 | } 139 | 140 | const manager = new DecoratorManager(); 141 | 142 | 143 | exports.saveClassMetadata = function saveClassMetadata(decoratorNameKey, data, target) { 144 | return manager.saveMetadata(decoratorNameKey, data, target); 145 | }; 146 | 147 | exports.attachClassMetadata = function attachClassMetadata(decoratorNameKey, data, target) { 148 | return manager.attachMetadata(decoratorNameKey, data, target); 149 | }; 150 | 151 | exports.getClassMetadata = function getClassMetadata(decoratorNameKey, target) { 152 | return manager.getMetadata(decoratorNameKey, target); 153 | }; 154 | 155 | exports.saveMethodDataToClass = function saveMethodDataToClass(decoratorNameKey, data, target, method) { 156 | return manager.savePropertyDataToClass(decoratorNameKey, data, target, method); 157 | }; 158 | 159 | exports.attachMethodDataToClass = function attachMethodDataToClass(decoratorNameKey, data, target, method) { 160 | return manager.attachPropertyDataToClass(decoratorNameKey, data, target, method); 161 | }; 162 | 163 | exports.getMethodDataFromClass = function getMethodDataFromClass(decoratorNameKey, target, method) { 164 | return manager.getPropertyDataFromClass(decoratorNameKey, target, method); 165 | }; 166 | 167 | 168 | exports.saveModule = function saveModule(decoratorNameKey, target) { 169 | return manager.saveModule(decoratorNameKey, target); 170 | }; 171 | 172 | exports.listModule = function listModule(decoratorNameKey) { 173 | return manager.listModule(decoratorNameKey); 174 | }; 175 | 176 | // extends 177 | exports.getParamTypes = function getParamTypes(target, method) { 178 | return Reflect.getMetadata(PARAMTYPES_METADATA, target.prototype, method); 179 | }; 180 | 181 | exports.defineMetadata = function defineMetadata(metadataKey, value, target) { 182 | return Reflect.defineMetadata(metadataKey, value, target); 183 | }; 184 | 185 | exports.getMetadata = function getMetadata(metadataKey, target) { 186 | return Reflect.getMetadata(metadataKey, target); 187 | }; 188 | 189 | -------------------------------------------------------------------------------- /lib/exceptions/constant.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | exports.HttpStatus = { 3 | CONTINUE: 100, 4 | SWITCHING_PROTOCOLS: 101, 5 | PROCESSING: 102, 6 | OK: 200, 7 | CREATED: 201, 8 | ACCEPTED: 202, 9 | NON_AUTHORITATIVE_INFORMATION: 203, 10 | NO_CONTENT: 204, 11 | RESET_CONTENT: 205, 12 | PARTIAL_CONTENT: 206, 13 | AMBIGUOUS: 300, 14 | MOVED_PERMANENTLY: 301, 15 | FOUND: 302, 16 | SEE_OTHER: 303, 17 | NOT_MODIFIED: 304, 18 | TEMPORARY_REDIRECT: 307, 19 | PERMANENT_REDIRECT: 308, 20 | BAD_REQUEST: 400, 21 | UNAUTHORIZED: 401, 22 | PAYMENT_REQUIRED: 402, 23 | FORBIDDEN: 403, 24 | NOT_FOUND: 404, 25 | METHOD_NOT_ALLOWED: 405, 26 | NOT_ACCEPTABLE: 406, 27 | PROXY_AUTHENTICATION_REQUIRED: 407, 28 | REQUEST_TIMEOUT: 408, 29 | CONFLICT: 409, 30 | GONE: 410, 31 | LENGTH_REQUIRED: 411, 32 | PRECONDITION_FAILED: 412, 33 | PAYLOAD_TOO_LARGE: 413, 34 | URI_TOO_LONG: 414, 35 | UNSUPPORTED_MEDIA_TYPE: 415, 36 | REQUESTED_RANGE_NOT_SATISFIABLE: 416, 37 | EXPECTATION_FAILED: 417, 38 | I_AM_A_TEAPOT: 418, 39 | UNPROCESSABLE_ENTITY: 422, 40 | TOO_MANY_REQUESTS: 429, 41 | INTERNAL_SERVER_ERROR: 500, 42 | NOT_IMPLEMENTED: 501, 43 | BAD_GATEWAY: 502, 44 | SERVICE_UNAVAILABLE: 503, 45 | GATEWAY_TIMEOUT: 504, 46 | HTTP_VERSION_NOT_SUPPORTED: 505, 47 | }; 48 | -------------------------------------------------------------------------------- /lib/exceptions/exception.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const is = require('is-type-of'); 3 | const HttpStatus = require('./constant').HttpStatus; 4 | 5 | function createHttpExceptionBody(message, error, statusCode) { 6 | if (!message) { 7 | return { statusCode, error }; 8 | } 9 | return is.object(message) && !Array.isArray(message) 10 | ? message 11 | : { statusCode, error, message }; 12 | } 13 | 14 | class HttpException extends Error { 15 | constructor(response, status) { 16 | super(); 17 | this.message = response; 18 | this.response = response; 19 | this.status = status; 20 | } 21 | 22 | getResponse() { 23 | return this.response; 24 | } 25 | 26 | getStatus() { 27 | return this.status; 28 | } 29 | } 30 | 31 | exports.HttpException = HttpException; 32 | 33 | exports.ForbiddenException = class ForbiddenException extends HttpException { 34 | constructor(message, error = 'Forbidden') { 35 | super( 36 | createHttpExceptionBody(message, error, HttpStatus.FORBIDDEN), 37 | HttpStatus.FORBIDDEN 38 | ); 39 | } 40 | }; 41 | 42 | 43 | exports.BadRequestException = class BadRequestException extends HttpException { 44 | constructor(message, error = 'Bad Request') { 45 | super( 46 | createHttpExceptionBody(message, error, HttpStatus.BAD_REQUEST), 47 | HttpStatus.BAD_REQUEST 48 | ); 49 | } 50 | }; 51 | 52 | exports.UnauthorizedException = class UnauthorizedException extends HttpException { 53 | constructor(message, error = 'Unauthorized') { 54 | super( 55 | createHttpExceptionBody(message, error, HttpStatus.UNAUTHORIZED), 56 | HttpStatus.UNAUTHORIZED 57 | ); 58 | } 59 | }; 60 | 61 | exports.NotFoundException = class NotFoundException extends HttpException { 62 | constructor(message, error = 'Not Found') { 63 | super( 64 | createHttpExceptionBody(message, error, HttpStatus.NOT_FOUND), 65 | HttpStatus.NOT_FOUND 66 | ); 67 | } 68 | }; 69 | 70 | exports.NotAcceptableException = class NotAcceptableException extends HttpException { 71 | constructor(message, error = 'Not Acceptable') { 72 | super( 73 | createHttpExceptionBody(message, error, HttpStatus.NOT_ACCEPTABLE), 74 | HttpStatus.NOT_ACCEPTABLE 75 | ); 76 | } 77 | }; 78 | exports.RequestTimeoutException = class RequestTimeoutException extends HttpException { 79 | constructor(message, error = 'Request Timeout') { 80 | super( 81 | createHttpExceptionBody(message, error, HttpStatus.REQUEST_TIMEOUT), 82 | HttpStatus.REQUEST_TIMEOUT 83 | ); 84 | } 85 | }; 86 | 87 | exports.ConflictException = class ConflictException extends HttpException { 88 | constructor(message, error = 'Conflict') { 89 | super( 90 | createHttpExceptionBody(message, error, HttpStatus.CONFLICT), 91 | HttpStatus.CONFLICT 92 | ); 93 | } 94 | }; 95 | exports.GoneException = class GoneException extends HttpException { 96 | constructor(message, error = 'Gone') { 97 | super( 98 | createHttpExceptionBody(message, error, HttpStatus.GONE), 99 | HttpStatus.GONE 100 | ); 101 | } 102 | }; 103 | exports.PayloadTooLargeException = class PayloadTooLargeException extends HttpException { 104 | constructor(message, error = 'Payload Too Large') { 105 | super( 106 | createHttpExceptionBody(message, error, HttpStatus.PAYLOAD_TOO_LARGE), 107 | HttpStatus.PAYLOAD_TOO_LARGE 108 | ); 109 | } 110 | }; 111 | 112 | exports.UnsupportedMediaTypeException = class UnsupportedMediaTypeException extends HttpException { 113 | constructor(message, error = 'Unsupported Media Type') { 114 | super( 115 | createHttpExceptionBody( 116 | message, 117 | error, 118 | HttpStatus.UNSUPPORTED_MEDIA_TYPE 119 | ), 120 | HttpStatus.UNSUPPORTED_MEDIA_TYPE 121 | ); 122 | } 123 | }; 124 | 125 | exports.UnprocessableEntityException = class UnprocessableEntityException extends HttpException { 126 | constructor(message, error = 'Unprocessable Entity') { 127 | super( 128 | createHttpExceptionBody(message, error, HttpStatus.UNPROCESSABLE_ENTITY), 129 | HttpStatus.UNPROCESSABLE_ENTITY 130 | ); 131 | } 132 | }; 133 | exports.InternalServerErrorException = class InternalServerErrorException extends HttpException { 134 | constructor(message, error = 'Internal Server Error') { 135 | super( 136 | createHttpExceptionBody(message, error, HttpStatus.INTERNAL_SERVER_ERROR), 137 | HttpStatus.INTERNAL_SERVER_ERROR 138 | ); 139 | } 140 | }; 141 | 142 | exports.NotImplementedException = class NotImplementedException extends HttpException { 143 | constructor(message, error = 'Not Implemented') { 144 | super( 145 | createHttpExceptionBody(message, error, HttpStatus.NOT_IMPLEMENTED), 146 | HttpStatus.NOT_IMPLEMENTED 147 | ); 148 | } 149 | }; 150 | 151 | exports.BadGatewayException = class BadGatewayException extends HttpException { 152 | constructor(message, error = 'Bad Gateway') { 153 | super( 154 | createHttpExceptionBody(message, error, HttpStatus.BAD_GATEWAY), 155 | HttpStatus.BAD_GATEWAY 156 | ); 157 | } 158 | }; 159 | 160 | exports.ServiceUnavailableException = class ServiceUnavailableException extends HttpException { 161 | constructor(message, error = 'Service Unavailable') { 162 | super( 163 | createHttpExceptionBody(message, error, HttpStatus.SERVICE_UNAVAILABLE), 164 | HttpStatus.SERVICE_UNAVAILABLE 165 | ); 166 | } 167 | }; 168 | 169 | 170 | exports.GatewayTimeoutException = class GatewayTimeoutException extends HttpException { 171 | constructor(message, error = 'Gateway Timeout') { 172 | super( 173 | createHttpExceptionBody(message, error, HttpStatus.GATEWAY_TIMEOUT), 174 | HttpStatus.GATEWAY_TIMEOUT 175 | ); 176 | } 177 | }; 178 | -------------------------------------------------------------------------------- /lib/loader/egg_loader.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const is = require('is-type-of'); 4 | const assert = require('assert'); 5 | const inflection = require('inflection'); 6 | 7 | const { safeRequire } = require('../utils'); 8 | const { REST_MAP, PATH_METADATA, PRIORITY_METADATA, CONTROLLER_MODULE_METADATA, ROUTE_OPTIONS_METADATA } = require('../constants'); 9 | 10 | const FileLoader = require('./file_loader'); 11 | const EggFileLoader = require('egg-core/lib/loader/file_loader'); 12 | 13 | const RouterProxy = require('../proxy/router_proxy'); 14 | const ContextCreator = require('../proxy/context_creator'); 15 | const ExceptionHandler = require('../proxy/exception_handler'); 16 | const RouterParamFactory = require('../proxy/router_param_factory'); 17 | 18 | const EggRouter = safeRequire('egg-core/lib/utils/router') || require('@eggjs/router').EggRouter; 19 | 20 | const { listModule, getClassMetadata } = require('../decorator_manager'); 21 | 22 | const ConfigValidator = { 23 | 24 | validate(config) { 25 | return { 26 | globalPipes: this.validPipes(config.globalPipes), 27 | globalGuards: this.validGuards(config.globalGuards), 28 | globalFilters: this.validFilters(config.globalFilters), 29 | globalInterceptors: this.validInterceptors(config.globalInterceptors), 30 | }; 31 | }, 32 | 33 | validPipes(pipes = []) { 34 | assert(Array.isArray(pipes), 'global pipes should be array'); 35 | return pipes.filter(pipe => pipe && (is.function(pipe) || is.function(pipe.transform))); 36 | }, 37 | 38 | validGuards(guards = []) { 39 | assert(Array.isArray(guards), 'global guards should be array'); 40 | return guards.filter(guard => guard && (is.function(guard) || is.function(guard.canActivate))); 41 | }, 42 | 43 | validFilters(filters = []) { 44 | assert(Array.isArray(filters), 'global filters should be array'); 45 | return filters.filter(filter => filter && (is.function(filter) || is.function(filter.catch))); 46 | }, 47 | 48 | validInterceptors(interceptors = []) { 49 | assert(Array.isArray(interceptors), 'global interceptors should be array'); 50 | return interceptors.filter(interceptor => interceptor && (is.function(interceptor) || is.function(interceptor.intercept))); 51 | }, 52 | 53 | }; 54 | 55 | 56 | module.exports = { 57 | 58 | 59 | // router priority 60 | prioritySortRouters: [], 61 | 62 | 63 | loadToApp(directory, property, opt) { 64 | 65 | const target = this.app[property] = {}; 66 | opt = Object.assign({}, { 67 | directory, 68 | target, 69 | inject: this.app, 70 | }, opt); 71 | 72 | const timingKey = `Load "${String(property)}" to Application`; 73 | this.timing.start(timingKey); 74 | // when load controller use custom fileloder 75 | if (property === 'controller') { 76 | new FileLoader(opt).load(); 77 | } else { 78 | new EggFileLoader(opt).load(); 79 | } 80 | this.timing.end(timingKey); 81 | }, 82 | 83 | 84 | /** 85 | * create controller method proxy 86 | */ 87 | createMethodsProxy() { 88 | 89 | const globalFeatures = ConfigValidator.validate(this.config); 90 | 91 | const routerParamFactory = new RouterParamFactory(); 92 | const contextCreator = new ContextCreator(globalFeatures); 93 | const routerProxy = new RouterProxy(contextCreator, ExceptionHandler, routerParamFactory); 94 | 95 | const controllerModules = listModule(CONTROLLER_MODULE_METADATA); 96 | 97 | for (const controller of controllerModules) { 98 | const controllerMetadata = getClassMetadata(PATH_METADATA, controller); 99 | const priorityMetadata = getClassMetadata(PRIORITY_METADATA, controller); 100 | const routerMetadatas = getClassMetadata(ROUTE_OPTIONS_METADATA, controller) || []; 101 | if (Array.isArray(routerMetadatas) && routerMetadatas.length !== 0) { 102 | for (const routerMetadata of routerMetadatas) { 103 | routerProxy.createCallbackProxy({ method: routerMetadata.method, targetCallback: routerMetadata.targetCallback }, controller); 104 | } 105 | } 106 | if (controllerMetadata.isRestful) { 107 | for (const key in REST_MAP) { 108 | const targetCallback = controller.prototype[key]; 109 | if (targetCallback) { 110 | routerProxy.createCallbackProxy({ method: key, targetCallback }, controller); 111 | } 112 | } 113 | } 114 | this.resolveRouters(controller, controllerMetadata, priorityMetadata, routerMetadatas); 115 | } 116 | 117 | 118 | // implement @Piority 119 | this.app.beforeStart(() => { 120 | this.prioritySortRouters 121 | .sort((routerA, routerB) => routerB.priority - routerA.priority) 122 | .forEach(prioritySortRouter => { 123 | this.app.router.use(prioritySortRouter.router.routes()); 124 | }); 125 | }); 126 | 127 | 128 | }, 129 | 130 | resolveRouters(controller, controllerMetadta, priority, routerMetadatas) { 131 | 132 | const { name, prefix, isRestful, routerOptions } = controllerMetadta; 133 | 134 | // prefix ='/xxx/' => '/xxx' 135 | let basePath = prefix.replace(/\/$/, ''); 136 | // prefix = '/' then tranfrom into '' 137 | basePath = basePath.length === 1 ? '' : basePath; 138 | 139 | 140 | const router = this.createEggRouter(basePath, routerOptions); 141 | 142 | this.handlerWebMiddleware(routerOptions.middleware, middlewareImpl => { 143 | router.use(middlewareImpl); 144 | }); 145 | 146 | 147 | for (const pathProperty of routerMetadatas) { 148 | 149 | const { path, paramOptions, requestMethod, method } = pathProperty; 150 | const methodMiddlewares = []; 151 | 152 | if (paramOptions) { 153 | this.handlerWebMiddleware(paramOptions.middleware, middlewareImpl => { 154 | methodMiddlewares.push(middlewareImpl); 155 | }); 156 | } 157 | // const targetcallback = this.getTargetCallback(properties, method); 158 | 159 | const targetCallback = FileLoader.methodToMiddleware(controller, method); 160 | 161 | const routerArgs = paramOptions 162 | ? [paramOptions.routerName, path, ...methodMiddlewares, targetCallback].filter(x => x) 163 | : [path, ...methodMiddlewares, targetCallback]; 164 | 165 | 166 | router[requestMethod].apply(router, routerArgs); 167 | 168 | 169 | } 170 | 171 | if (prefix && isRestful) { 172 | // resources verb 173 | this.register(router, controller, { name, prefix: '/' }); 174 | } 175 | 176 | this.prioritySortRouters.push({ priority, router }); 177 | 178 | 179 | }, 180 | 181 | 182 | // rewrite register because app.controller is not defined 183 | register(router, controller, { name, prefix }) { 184 | 185 | for (const key in REST_MAP) { 186 | 187 | let formatedName; 188 | 189 | const opts = REST_MAP[key]; 190 | 191 | 192 | if (!controller.prototype[key]) continue; 193 | 194 | const action = FileLoader.methodToMiddleware(controller, key); 195 | 196 | if (opts.member) { 197 | formatedName = inflection.singularize(name); 198 | } else { 199 | formatedName = inflection.pluralize(name); 200 | } 201 | 202 | if (opts.namePrefix) { 203 | formatedName = opts.namePrefix + formatedName; 204 | } 205 | 206 | const path = opts.suffix ? `${prefix}${opts.suffix}` : prefix; 207 | const method = Array.isArray(opts.method) ? opts.method : [opts.method]; 208 | router.register(path, method, action, { name: formatedName }); 209 | } 210 | 211 | }, 212 | 213 | // get egg controller method 214 | // getTargetCallback(properties, method) { 215 | // properties.push(method); 216 | // const targetCallback = path(properties.join('.'), this.app.controller); 217 | // properties.pop(); 218 | // return targetCallback; 219 | // }, 220 | 221 | 222 | createEggRouter(basePath, routerOptions) { 223 | if (basePath) { 224 | const { sensitive = true } = routerOptions; 225 | const router = new EggRouter({ prefix: this.getGlobalPrefix() + basePath, sensitive }, this.app); 226 | return router; 227 | } 228 | 229 | return new EggRouter({ sensitive: true }, this.app); 230 | }, 231 | 232 | 233 | handlerWebMiddleware(middlewares, handlerCallback) { 234 | if (middlewares && middlewares.length) { 235 | for (const m of middlewares) { 236 | let finalArgs; 237 | if (is.asyncFunction(m)) { 238 | finalArgs = m; 239 | } else if (is.function(m)) { 240 | if (m.name === '') { 241 | finalArgs = m(); 242 | } else { 243 | finalArgs = m(this.app.config[m.name]); 244 | } 245 | } else { 246 | finalArgs = this.app.middleware[m](this.app.config[m]); 247 | } 248 | handlerCallback(finalArgs); 249 | } 250 | } 251 | }, 252 | 253 | getGlobalPrefix() { 254 | let path = this.globalPrefix = this.config.globalPrefix || ''; 255 | assert(is.string(path), 'globalPrefix must be a string'); 256 | const validatePath = path => (path.charAt(0) !== '/' ? '/' + path : path); 257 | path = path ? validatePath(path) : path; 258 | path = path ? path.replace(/\/$/, '') : path; 259 | this.globalPrefix = path; 260 | return path; 261 | }, 262 | 263 | 264 | }; 265 | -------------------------------------------------------------------------------- /lib/loader/file_loader.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const fs = require('fs'); 3 | const is = require('is-type-of'); 4 | const path = require('path'); 5 | const assert = require('assert'); 6 | const globby = require('globby'); 7 | 8 | const debug = require('debug')('egg-core:loader'); 9 | 10 | const { utils } = require('egg-core'); 11 | const EggFileLoader = require('egg-core/lib/loader/file_loader'); 12 | 13 | const FULLPATH = Symbol.for('EGG_LOADER_ITEM_FULLPATH'); 14 | // const EXPORTS = Symbol.for('EGG_LOADER_ITEM_EXPORTS'); 15 | 16 | 17 | class FileLoader extends EggFileLoader { 18 | 19 | // loadCustom 阶段如果要用装饰路由就得重新绑定 ctx; 20 | static methodToMiddleware(Controller, key) { 21 | return function classControllerMiddleware(...args) { 22 | 23 | let controller; 24 | // no extends 25 | if (Object.getPrototypeOf(Controller.prototype) === Object.prototype) { 26 | controller = new Controller(); 27 | controller.ctx = this; 28 | controller.app = this.app; 29 | controller.config = this.app.config; 30 | controller.service = this.service; 31 | } else { 32 | controller = new Controller(this); 33 | } 34 | if (!this.app.config.controller || !this.app.config.controller.supportParams) { 35 | args = [ this ]; 36 | } 37 | return utils.callFn(controller[key], args, controller); 38 | }; 39 | } 40 | 41 | parse() { 42 | 43 | let files = this.options.match; 44 | if (!files) { 45 | files = (process.env.EGG_TYPESCRIPT === 'true' && utils.extensions['.ts']) 46 | ? [ '**/*.(js|ts)', '!**/*.d.ts' ] 47 | : [ '**/*.js' ]; 48 | } else { 49 | files = Array.isArray(files) ? files : [ files ]; 50 | } 51 | 52 | let ignore = this.options.ignore; 53 | if (ignore) { 54 | ignore = Array.isArray(ignore) ? ignore : [ ignore ]; 55 | ignore = ignore.filter(f => !!f).map(f => '!' + f); 56 | files = files.concat(ignore); 57 | } 58 | 59 | let directories = this.options.directory; 60 | if (!Array.isArray(directories)) { 61 | directories = [ directories ]; 62 | } 63 | 64 | const filter = is.function(this.options.filter) ? this.options.filter : null; 65 | const items = []; 66 | 67 | debug('parsing %j', directories); 68 | for (const directory of directories) { 69 | const filepaths = globby.sync(files, { cwd: directory }); 70 | for (const filepath of filepaths) { 71 | const fullpath = path.join(directory, filepath); 72 | if (!fs.statSync(fullpath).isFile()) continue; 73 | // get properties 74 | // app/service/foo/bar.js => [ 'foo', 'bar' ] 75 | const properties = getProperties(filepath, this.options); 76 | // app/service/foo/bar.js => service.foo.bar 77 | const pathName = directory.split(/[/\\]/).slice(-1) + '.' + properties.join('.'); 78 | // get exports from the file 79 | const exports = loadController(fullpath, { path: fullpath, pathName }); 80 | 81 | // ignore exports when it's null or false returned by filter function 82 | if (exports == null || (filter && filter(exports) === false)) continue; 83 | 84 | // set properties of class 85 | if (is.class(exports)) { 86 | exports.prototype.pathName = pathName; 87 | exports.prototype.fullPath = fullpath; 88 | } 89 | 90 | items.push({ fullpath, properties, exports }); 91 | 92 | debug('parse %s, properties %j, export %j', fullpath, properties, exports); 93 | } 94 | } 95 | return items; 96 | } 97 | 98 | 99 | } 100 | 101 | // load controller 102 | function loadController(fullpath, opt) { 103 | let controller; 104 | const exports = utils.loadFile(fullpath); 105 | const isClass = module => is.class(module) || is.function(module); 106 | if (isClass(exports)) { 107 | controller = exports; 108 | } else { 109 | for (const m in exports) { 110 | const module = exports[m]; 111 | if (isClass(module)) { 112 | controller = module; 113 | } 114 | } 115 | } 116 | controller.prototype.pathName = opt.pathName; 117 | controller.prototype.fullPath = opt.path; 118 | return wrapClass(controller); 119 | } 120 | 121 | function wrapClass(controller) { 122 | let proto = controller.prototype; 123 | const ret = {}; 124 | // tracing the prototype chain 125 | while (proto !== Object.prototype) { 126 | const keys = Object.getOwnPropertyNames(proto); 127 | for (const key of keys) { 128 | // getOwnPropertyNames will return constructor 129 | // that should be ignored 130 | if (key === 'constructor') { 131 | continue; 132 | } 133 | // skip getter, setter & non-function properties 134 | const d = Object.getOwnPropertyDescriptor(proto, key); 135 | // prevent to override sub method 136 | if (is.function(d.value) && !ret.hasOwnProperty(key)) { 137 | ret[key] = FileLoader.methodToMiddleware(controller, key); 138 | ret[key][FULLPATH] = controller.prototype.fullPath + '#' + controller.name + '.' + key + '()'; 139 | } 140 | } 141 | proto = Object.getPrototypeOf(proto); 142 | } 143 | return ret; 144 | 145 | } 146 | 147 | function getProperties(filepath, { caseStyle }) { 148 | // if caseStyle is function, return the result of function 149 | if (is.function(caseStyle)) { 150 | const result = caseStyle(filepath); 151 | assert(is.array(result), `caseStyle expect an array, but got ${result}`); 152 | return result; 153 | } 154 | // use default camelize 155 | return defaultCamelize(filepath, caseStyle); 156 | } 157 | 158 | function defaultCamelize(filepath, caseStyle) { 159 | const properties = filepath.substring(0, filepath.lastIndexOf('.')).split('/'); 160 | return properties.map(property => { 161 | if (!/^[a-z][a-z0-9_-]*$/i.test(property)) { 162 | throw new Error(`${property} is not match 'a-z0-9_-' in ${filepath}`); 163 | } 164 | 165 | // use default camelize, will capitalize the first letter 166 | // foo_bar.js > FooBar 167 | // fooBar.js > FooBar 168 | // FooBar.js > FooBar 169 | // FooBar.js > FooBar 170 | // FooBar.js > fooBar (if lowercaseFirst is true) 171 | property = property.replace(/[_-][a-z]/ig, s => s.substring(1).toUpperCase()); 172 | let first = property[0]; 173 | switch (caseStyle) { 174 | case 'lower': 175 | first = first.toLowerCase(); 176 | break; 177 | case 'upper': 178 | first = first.toUpperCase(); 179 | break; 180 | case 'camel': 181 | default: 182 | } 183 | return first + property.substring(1); 184 | }); 185 | } 186 | 187 | module.exports = FileLoader; 188 | -------------------------------------------------------------------------------- /lib/proxy/context_creator.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const is = require('is-type-of'); 3 | const { 4 | GUARDS_METADATA, 5 | PIPES_METADATA, 6 | INTERCEPTORS_METADATA, 7 | EXCEPTION_FILTERS_METADATA, 8 | FILTER_CATCH_EXCEPTIONS, 9 | } = require('../constants'); 10 | 11 | 12 | const { getClassMetadata, getMethodDataFromClass } = require('../decorator_manager'); 13 | 14 | class ContextCreator { 15 | 16 | constructor(config = {}) { 17 | this.config = config; 18 | } 19 | 20 | createFeatures(controller, key) { 21 | return { 22 | pipes: this.createPipes(controller, key), 23 | guards: this.createGuards(controller, key), 24 | filters: this.createFilters(controller, key), 25 | interceptors: this.createInterceptors(controller, key), 26 | }; 27 | } 28 | 29 | /** 30 | * 31 | * @param {Function} controller : controller 32 | * @param {string} key : controller method name 33 | * @return {object[]} proto: all of guardsprototype 34 | */ 35 | createGuards(controller, key) { 36 | return this.create(controller, key, GUARDS_METADATA, this.loadInstanceForGuards); 37 | } 38 | 39 | createPipes(controller, key) { 40 | return this.create(controller, key, PIPES_METADATA, this.loadInstanceForPipes); 41 | } 42 | 43 | createInterceptors(controller, key) { 44 | return this.create(controller, key, INTERCEPTORS_METADATA, this.loadInstanceForInterceptors); 45 | } 46 | 47 | createFilters(controller, key) { 48 | return this.create(controller, key, EXCEPTION_FILTERS_METADATA, this.loadInstanceForFilters); 49 | } 50 | 51 | /** 52 | * 53 | * @param {Function} controller : controller 54 | * @param {string} key : controller method name 55 | * @param {String} metadata : metadata : such GUAED_METADATA 56 | * @param {string} loadInstanceFnc : must implements method nmae : such 'canActivate' 57 | * @return {object[]} proto: guard prototype 58 | */ 59 | create(controller, key, metadata, loadInstanceFnc) { 60 | // const { getClassMetadata } = this.reflector; 61 | const globalMetadata = this.getGlobalMetadata(metadata); 62 | const classMetadata = getClassMetadata(metadata, controller); 63 | const methodMetadata = getMethodDataFromClass(metadata, controller, key); 64 | return [ 65 | ...this.getsFeaturesInstance(loadInstanceFnc, globalMetadata), 66 | ...this.getsFeaturesInstance(loadInstanceFnc, classMetadata), 67 | ...this.getsFeaturesInstance(loadInstanceFnc, methodMetadata), 68 | ]; 69 | } 70 | 71 | // get pipes/guards/interceptors/filter instance 72 | getsFeaturesInstance(loadInstanceFnc, metadata) { 73 | if (is.nullOrUndefined(metadata)) return []; 74 | return metadata.map(loadInstanceFnc); 75 | } 76 | 77 | loadInstanceForGuards(injectable) { 78 | // injectable.name === '' means injectable is class {} 79 | const isValidGuard = (injectable.name || injectable.name === '') && !is.function(injectable.canActivate); 80 | return isValidGuard ? Reflect.construct(injectable, []) : injectable; 81 | } 82 | 83 | loadInstanceForPipes(injectable) { 84 | const isValidPipe = (injectable.name || injectable.name === '') && !is.function(injectable.transform); 85 | return isValidPipe ? Reflect.construct(injectable, []) : injectable; 86 | } 87 | 88 | loadInstanceForInterceptors(injectable) { 89 | const isValidInterceptor = (injectable.name || injectable.name === '') && !is.function(injectable.intercept); 90 | return isValidInterceptor ? Reflect.construct(injectable, []) : injectable; 91 | } 92 | 93 | loadInstanceForFilters(injectable) { 94 | const isValidFilter = (injectable.name || injectable.name === '') && !is.function(injectable.catch); 95 | const injectableIns = isValidFilter ? Reflect.construct(injectable, []) : injectable; 96 | const exceptionMetatypes = ( 97 | isValidFilter 98 | ? getClassMetadata(FILTER_CATCH_EXCEPTIONS, injectable) 99 | : getClassMetadata(FILTER_CATCH_EXCEPTIONS, Object.getPrototypeOf(injectable).constructor) 100 | ) || []; 101 | return Object.assign(injectableIns, { exceptionMetatypes }); 102 | } 103 | 104 | getGlobalMetadata(metadata) { 105 | const config = this.config; 106 | if (metadata === GUARDS_METADATA) { 107 | return config.globalGuards; 108 | } 109 | if (metadata === PIPES_METADATA) { 110 | return config.globalPipes; 111 | } 112 | if (metadata === INTERCEPTORS_METADATA) { 113 | return config.globalInterceptors; 114 | } 115 | if (metadata === EXCEPTION_FILTERS_METADATA) { 116 | return config.globalFilters; 117 | } 118 | } 119 | 120 | doConstruct(injectable) { 121 | return Reflect.construct(injectable, []); 122 | } 123 | 124 | 125 | } 126 | 127 | 128 | module.exports = ContextCreator; 129 | 130 | -------------------------------------------------------------------------------- /lib/proxy/exception_handler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const is = require('is-type-of'); 3 | const { HttpException } = require('../exceptions/exception'); 4 | 5 | 6 | class ExceptionHanlder { 7 | 8 | static create(filters) { 9 | 10 | return new ExceptionHanlder(filters); 11 | 12 | } 13 | 14 | constructor(filters = []) { 15 | this.filters = filters; 16 | } 17 | 18 | next(exception, app) { 19 | const { ctx } = app; 20 | if (this.invokeCustomFilters(exception, app)) return; 21 | // common throw error 22 | if (!(exception instanceof HttpException)) throw exception; 23 | // custom exception which extends HttpException 24 | const res = exception.getResponse(); 25 | const message = is.object(res) 26 | ? res 27 | : { 28 | statusCode: exception.getStatus(), 29 | message: res, 30 | }; 31 | 32 | ctx.status = exception.getStatus(); 33 | if (is.nullOrUndefined(message)) { 34 | ctx.body = ''; 35 | return; 36 | } 37 | ctx.body = is.object(message) ? message : String(message); 38 | return; 39 | } 40 | 41 | invokeCustomFilters(exception, app) { 42 | if (!this.filters.length) return false; 43 | let filter = this.filters.find(filter => { 44 | const exceptionMetatypes = filter.exceptionMetatypes; 45 | const hasMetatype = 46 | !exceptionMetatypes.length || 47 | exceptionMetatypes.some( 48 | ExceptionMetatype => exception instanceof ExceptionMetatype 49 | ); 50 | return hasMetatype; 51 | }); 52 | if (filter) { 53 | filter = Object.assign(filter, app); 54 | filter.catch(exception); 55 | } 56 | return !!filter; 57 | } 58 | 59 | } 60 | 61 | /** 62 | * create Exceptionhandler class for callbackProxy exception handle; 63 | */ 64 | module.exports = ExceptionHanlder; 65 | 66 | -------------------------------------------------------------------------------- /lib/proxy/router_param_factory.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const { RouteParamTypes } = require('../constants'); 3 | 4 | class RouterParamFactory { 5 | 6 | /** 7 | * get ctx(context/request,response,body/param/queyr/headers/seesion) 8 | * @param {number} key :type of RouterParamtypes 9 | * @param {string|number|object} data : ParamData ; such @Body('id) 10 | * @return {object} ctx property 11 | */ 12 | extractValue(key, data) { 13 | return async function(ctx) { 14 | switch (key) { 15 | case RouteParamTypes.REQUEST: 16 | return ctx.request; 17 | case RouteParamTypes.RESPONSE: 18 | return ctx.response; 19 | case RouteParamTypes.BODY: 20 | return data && ctx.request.body ? ctx.request.body[data] : ctx.request.body; 21 | case RouteParamTypes.PARAM: 22 | return data ? ctx.params[data] : ctx.params; 23 | case RouteParamTypes.QUERY: 24 | return data ? ctx.query[data] : ctx.query; 25 | case RouteParamTypes.HEADERS: 26 | return data ? ctx.headers[data] : ctx.headers; 27 | case RouteParamTypes.SESSION: 28 | return ctx.session; 29 | case RouteParamTypes.FILE: 30 | return ctx.request.files[0]; 31 | case RouteParamTypes.FILES: 32 | return ctx.request.files; 33 | case RouteParamTypes.FILESTREAM: 34 | return ctx.getFileStream && await ctx.getFileStream(data); 35 | case RouteParamTypes.FILESSTREAM: 36 | return ctx.multipart && ctx.multipart(data); 37 | default: 38 | return null; 39 | } 40 | }; 41 | } 42 | 43 | } 44 | 45 | module.exports = RouterParamFactory; 46 | -------------------------------------------------------------------------------- /lib/proxy/router_proxy.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const is = require('is-type-of'); 3 | const { HttpStatus } = require('../exceptions/constant'); 4 | const { ForbiddenException } = require('../exceptions/exception'); 5 | const { switchMap, mergeAll } = require('rxjs/operators'); 6 | const { Observable, defer, from } = require('rxjs'); 7 | const { 8 | RequestMethod, 9 | RouteParamTypes, 10 | RENDER_METADATA, 11 | HEADER_METADATA, 12 | ROUTE_ARGS_METADATA, 13 | HTTP_CODE_METADATA, 14 | ROUTE_OPTIONS_METADATA, 15 | } = require('../constants'); 16 | 17 | const { getMethodDataFromClass, getClassMetadata, getParamTypes } = require('../decorator_manager'); 18 | 19 | 20 | class RouterProxy { 21 | 22 | constructor(contextCreator, exceptionHandler, routerParamFactory) { 23 | this.contextCreator = contextCreator; 24 | this.exceptionHandler = exceptionHandler; 25 | this.routerParamFactory = routerParamFactory; 26 | } 27 | 28 | // param 处理 29 | reflectCallbackParamtypes(klass, key) { 30 | const args = getMethodDataFromClass(ROUTE_ARGS_METADATA, klass, key) || {}; 31 | const { extractValue } = this.routerParamFactory; 32 | return Object.keys(args).reduce((arr, typeAndIndex) => { 33 | const [ type, index ] = typeAndIndex.split(':'); 34 | const { data, pipes, factory } = args[typeAndIndex]; 35 | arr.push({ 36 | index, 37 | type, 38 | data, 39 | pipes, 40 | factory, 41 | extractValue: extractValue(type, data), 42 | }); 43 | return arr; 44 | }, []); 45 | } 46 | 47 | 48 | createGuardsFn(guards, context) { 49 | const canActivateFn = async function() { 50 | const pickResult = async result => (result instanceof Observable 51 | ? await result.toPromise() 52 | : result); 53 | for (let guard of guards) { 54 | guard = Object.assign(guard, this); 55 | const result = await guard.canActivate(context); 56 | if (await pickResult(result)) { 57 | continue; 58 | } else { 59 | throw new ForbiddenException('Forbidden resource'); 60 | } 61 | } 62 | }; 63 | 64 | return guards.length ? canActivateFn : null; 65 | } 66 | 67 | 68 | createPipesFn(pipes, callbackParamtypes, parmTypes) { 69 | const { getsFeaturesInstance, loadInstanceForPipes } = this.contextCreator; 70 | const getCustomFactory = this.getCustomFactory.bind(this); 71 | const getPipesInstance = getsFeaturesInstance.bind(this, loadInstanceForPipes); 72 | const pipesFn = async function(args) { 73 | await Promise.all(callbackParamtypes.map(async param => { 74 | let value; 75 | let { index, type, data, pipes: paramPipes, factory, extractValue } = param; 76 | const metatype = parmTypes[index]; 77 | const paramType = RouteParamTypes[type]; 78 | paramPipes = getPipesInstance(paramPipes); 79 | if (factory) { 80 | value = getCustomFactory(factory)(data, this.ctx); 81 | } else { 82 | value = await extractValue(this.ctx); 83 | } 84 | if ( 85 | type === RouteParamTypes.QUERY || 86 | type === RouteParamTypes.PARAM || 87 | type === RouteParamTypes.BODY || 88 | is.string(type) 89 | ) { 90 | 91 | const allPipes = pipes.concat(paramPipes).map(pipe => Object.assign(pipe, this)); 92 | 93 | args[index] = await getParamValue( 94 | allPipes, 95 | value, 96 | { 97 | data, 98 | metatype, 99 | type: paramType, 100 | }); 101 | } else { 102 | args[index] = value; 103 | } 104 | })); 105 | }; 106 | 107 | async function getParamValue(pipes, value, metadata) { 108 | return await pipes.reduce(async (value, pipe) => { 109 | const val = await value; 110 | // pipe = Object.assign(pipe, this); 111 | const result = pipe.transform(val, metadata); 112 | return result; 113 | }, Promise.resolve(value)); 114 | } 115 | 116 | return callbackParamtypes.length ? pipesFn : null; 117 | } 118 | 119 | createInterceptorsFn(interceptors, context) { 120 | return async function intercept(handler) { 121 | if (!interceptors || !interceptors.length) return handler(); 122 | const start$ = defer(() => transformValue(handler)); 123 | const nextFn = (i = 0) => async () => { 124 | if (i >= interceptors.length) { 125 | return start$; 126 | } 127 | const handler = { 128 | handle: () => from(nextFn(i + 1)()).pipe(mergeAll()), 129 | }; 130 | const interceptor = Object.assign(interceptors[i], this); 131 | return interceptor.intercept(context, handler); 132 | }; 133 | return nextFn()(); 134 | }; 135 | 136 | function transformValue(next) { 137 | return from(next()).pipe( 138 | switchMap(res => { 139 | const isDeffered = res instanceof Promise || res instanceof Observable; 140 | return isDeffered ? res : Promise.resolve(res); 141 | }) 142 | ); 143 | } 144 | } 145 | 146 | createFinalHandler(controller, method) { 147 | const isEmpty = array => !(array && array.length > 0); 148 | const httpCode = getMethodDataFromClass(HTTP_CODE_METADATA, controller, method); 149 | const renderTemplate = getMethodDataFromClass(RENDER_METADATA, controller, method); 150 | const responseHeaders = getMethodDataFromClass(HEADER_METADATA, controller, method); 151 | const routerOptionsMetadatas = getClassMetadata(ROUTE_OPTIONS_METADATA, controller) || []; 152 | const routerOptionMetadata = routerOptionsMetadatas.filter(data => data.method === method); 153 | const { requestMethod } = routerOptionMetadata.length >= 1 ? routerOptionMetadata[0] : {}; 154 | const httpStatusCode = httpCode ? httpCode : requestMethod === RequestMethod.POST ? HttpStatus.CREATED : HttpStatus.OK; 155 | const hasCustomHeaders = !isEmpty(responseHeaders); 156 | // render 157 | if (renderTemplate) { 158 | return async (result, ctx) => { 159 | hasCustomHeaders && setHeaders(responseHeaders, ctx); 160 | result = await transformToResult(result); 161 | await ctx.render(renderTemplate, result); 162 | }; 163 | } 164 | 165 | return async (result, ctx) => { 166 | hasCustomHeaders && setHeaders(responseHeaders, ctx); 167 | result = await transformToResult(result); 168 | if (is.nullOrUndefined(result)) return; 169 | ctx.status = httpStatusCode; 170 | ctx.body = result; 171 | }; 172 | 173 | function setHeaders(headers, ctx) { 174 | headers.forEach(({ name, value }) => { 175 | // name => { key:value, key:value} 176 | if (!value) { 177 | ctx.set(name); 178 | return; 179 | } 180 | ctx.set(name, value); 181 | }); 182 | } 183 | 184 | async function transformToResult(resultOrDeffered) { 185 | if (resultOrDeffered && is.function(resultOrDeffered.subscribe)) { 186 | return await resultOrDeffered.toPromise(); 187 | } 188 | return resultOrDeffered; 189 | } 190 | } 191 | 192 | // for custom decorators 193 | getCustomFactory(factory) { 194 | return !is.undefined(factory) && is.function(factory) 195 | ? factory 196 | : () => null; 197 | } 198 | 199 | // use context for guard/interceptor 200 | createContext(controller, method) { 201 | return { 202 | getClass() { 203 | return controller; 204 | }, 205 | getHandler() { 206 | return method; 207 | }, 208 | }; 209 | } 210 | 211 | createCallbackProxy(routerProperty, controller) { 212 | 213 | 214 | const { method, targetCallback } = routerProperty; 215 | const { pipes, guards, filters, interceptors } = this.contextCreator.createFeatures(controller, method); 216 | 217 | 218 | const context = this.createContext(controller, targetCallback); 219 | const fnCanActivate = this.createGuardsFn(guards, context); 220 | 221 | const paramTypes = getParamTypes(controller, method); 222 | const callbackParamtypes = this.reflectCallbackParamtypes(controller, method); 223 | const canTransformFn = this.createPipesFn(pipes, callbackParamtypes, paramTypes); 224 | 225 | const interceptorFn = this.createInterceptorsFn(interceptors, context); 226 | const fnHandleResponse = this.createFinalHandler(controller, method); 227 | 228 | 229 | const exceptionHanlder = this.exceptionHandler.create(filters.reverse()); 230 | 231 | 232 | async function callbackProxy() { 233 | const args = Array.apply(null, { length: callbackParamtypes.length }).fill(null); 234 | // guard 235 | fnCanActivate && await fnCanActivate.call(this); 236 | // pipe and targetcallback 237 | const handler = async () => { 238 | canTransformFn && await canTransformFn.call(this, args); 239 | return await targetCallback.apply(this, args); 240 | }; 241 | // intercept 242 | const result = await interceptorFn.call(this, handler); 243 | await fnHandleResponse(result, this.ctx); 244 | } 245 | 246 | Object.defineProperty(controller.prototype, method, { 247 | async value() { 248 | 249 | try { 250 | await callbackProxy.call(this); 251 | } catch (e) { 252 | exceptionHanlder.next(e, this); 253 | } 254 | 255 | }, 256 | writable: false, 257 | configurable: false, 258 | } 259 | ); 260 | 261 | } 262 | 263 | } 264 | 265 | module.exports = RouterProxy; 266 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const utils = module.exports = { }; 4 | 5 | const MissingRequiredDependency = (name, reason) => 6 | `The "${name}" package is missing. Please, make sure to install this library ($ npm install ${name} / or require) to take advantage of ${reason}.`; 7 | 8 | 9 | utils.loadPackage = function loadPackage(packageName, context) { 10 | try { 11 | return require(packageName); 12 | } catch (e) { 13 | throw new Error(MissingRequiredDependency(packageName, context)); 14 | } 15 | }; 16 | 17 | utils.safeRequire = function require(packageName) { 18 | try { 19 | return require(packageName); 20 | } catch (e) { 21 | return undefined; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "egg-pig", 3 | "description": "nestjs in egg", 4 | "keywords": [ 5 | "egg", 6 | "eggPlugin", 7 | "egg-plugin", 8 | "Decorators", 9 | "nest", 10 | "nestjs" 11 | ], 12 | "author": "YV", 13 | "license": "ISC", 14 | "main": "index.js", 15 | "eggPlugin": { 16 | "name": "eggpig" 17 | }, 18 | "bugs": { 19 | "url": "https://github.com/yviscool/egg-pig/issues" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/yviscool/egg-pig" 24 | }, 25 | "dependencies": { 26 | "@eggjs/router": "^2.0.0", 27 | "globby": "^9.2.0", 28 | "inflection": "^1.12.0", 29 | "is-type-of": "^1.2.0", 30 | "reflect-metadata": "^0.1.13", 31 | "rxjs": "^6.6.2", 32 | "uuid": "^8.3.0", 33 | "class-transformer": "^0.3.1", 34 | "class-validator": "^0.12.2" 35 | }, 36 | "devDependencies": { 37 | "autod": "^3.0.1", 38 | "autod-egg": "^1.0.0", 39 | "await-stream-ready": "^1.0.1", 40 | "egg": "^2.21.1", 41 | "egg-bin": "^4.12.3", 42 | "egg-ci": "^1.11.0", 43 | "egg-mock": "^3.22.2", 44 | "egg-view-nunjucks": "^2.2.0", 45 | "eslint": "^5.16.0", 46 | "eslint-config-egg": "^7.3.1", 47 | "mz": "^2.7.0", 48 | "mz-modules": "^2.1.0", 49 | "stream-wormhole": "^1.0.3", 50 | "tslib": "^1.9.0", 51 | "tslint": "^5.15.0", 52 | "webstorm-disable-index": "^1.2.0" 53 | }, 54 | "engines": { 55 | "node": ">=8.9.0" 56 | }, 57 | "scripts": { 58 | "test": "egg-bin test", 59 | "cov": "egg-bin cov", 60 | "lint": "eslint .", 61 | "ci": "npm run lint -- --fix && npm run cov", 62 | "autod": "autod" 63 | }, 64 | "version": "1.0.2" 65 | } 66 | -------------------------------------------------------------------------------- /test/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yviscool/egg-pig/0c1414d7c6434d663ad8bcd07d6983585b6eab02/test/1.jpg -------------------------------------------------------------------------------- /test/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yviscool/egg-pig/0c1414d7c6434d663ad8bcd07d6983585b6eab02/test/2.jpg -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/context.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let ContextController = class ContextController { 7 | async query(query) { 8 | this.ctx.body = query.id; 9 | } 10 | async param(param) { 11 | this.ctx.body = param; 12 | } 13 | async headers(headers) { 14 | this.ctx.body = headers.host.substring(0,3); 15 | } 16 | async headersTwo(host) { 17 | this.ctx.body = host.substring(0,3); 18 | } 19 | async request(req) { 20 | this.ctx.body = req.method; 21 | } 22 | async response(res) { 23 | res.body = 'ok'; 24 | } 25 | async session(session) { 26 | this.ctx.body = session; 27 | } 28 | async ctx2(ctx) { 29 | ctx.body = 'ok'; 30 | } 31 | async body(body) { 32 | this.ctx.body = body; 33 | } 34 | }; 35 | tslib_1.__decorate([ 36 | egg_pig_1.Get('/query'), 37 | tslib_1.__param(0, egg_pig_1.Query()), 38 | tslib_1.__metadata("design:type", Function), 39 | tslib_1.__metadata("design:paramtypes", [Object]), 40 | tslib_1.__metadata("design:returntype", Promise) 41 | ], ContextController.prototype, "query", null); 42 | tslib_1.__decorate([ 43 | egg_pig_1.Get('/param/:id'), 44 | tslib_1.__param(0, egg_pig_1.Param('id')), 45 | tslib_1.__metadata("design:type", Function), 46 | tslib_1.__metadata("design:paramtypes", [Object]), 47 | tslib_1.__metadata("design:returntype", Promise) 48 | ], ContextController.prototype, "param", null); 49 | tslib_1.__decorate([ 50 | egg_pig_1.Get('/headers'), 51 | tslib_1.__param(0, egg_pig_1.Headers()), 52 | tslib_1.__metadata("design:type", Function), 53 | tslib_1.__metadata("design:paramtypes", [Object]), 54 | tslib_1.__metadata("design:returntype", Promise) 55 | ], ContextController.prototype, "headers", null); 56 | tslib_1.__decorate([ 57 | egg_pig_1.Get('/headers_two'), 58 | tslib_1.__param(0, egg_pig_1.Headers('host')), 59 | tslib_1.__metadata("design:type", Function), 60 | tslib_1.__metadata("design:paramtypes", [Object]), 61 | tslib_1.__metadata("design:returntype", Promise) 62 | ], ContextController.prototype, "headersTwo", null); 63 | tslib_1.__decorate([ 64 | egg_pig_1.Get('/request'), 65 | tslib_1.__param(0, egg_pig_1.Request()), 66 | tslib_1.__metadata("design:type", Function), 67 | tslib_1.__metadata("design:paramtypes", [Object]), 68 | tslib_1.__metadata("design:returntype", Promise) 69 | ], ContextController.prototype, "request", null); 70 | tslib_1.__decorate([ 71 | egg_pig_1.Get('/response'), 72 | tslib_1.__param(0, egg_pig_1.Response()), 73 | tslib_1.__metadata("design:type", Function), 74 | tslib_1.__metadata("design:paramtypes", [Object]), 75 | tslib_1.__metadata("design:returntype", Promise) 76 | ], ContextController.prototype, "response", null); 77 | tslib_1.__decorate([ 78 | egg_pig_1.Get('/session'), 79 | tslib_1.__param(0, egg_pig_1.Session()), 80 | tslib_1.__metadata("design:type", Function), 81 | tslib_1.__metadata("design:paramtypes", [Object]), 82 | tslib_1.__metadata("design:returntype", Promise) 83 | ], ContextController.prototype, "session", null); 84 | tslib_1.__decorate([ 85 | egg_pig_1.Post('/body'), 86 | tslib_1.__param(0, egg_pig_1.Body()), 87 | tslib_1.__metadata("design:type", Function), 88 | tslib_1.__metadata("design:paramtypes", [Object]), 89 | tslib_1.__metadata("design:returntype", Promise) 90 | ], ContextController.prototype, "body", null); 91 | ContextController = tslib_1.__decorate([ 92 | egg_pig_1.Controller('context') 93 | ], ContextController); 94 | exports.default = ContextController; 95 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29udGV4dC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImNvbnRleHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEsNkJBQXVDO0FBQ3ZDLHFDQUFrSDtBQUtsSCxJQUFNLGlCQUFpQixHQUF2Qix1QkFBd0IsU0FBUSxzQkFBZ0I7SUFHNUMsS0FBSyxDQUFDLEtBQUssQ0FBVSxLQUFLO1FBQ3RCLElBQUksQ0FBQyxHQUFHLENBQUMsSUFBSSxHQUFHLEtBQUssQ0FBQyxFQUFFLENBQUM7SUFDN0IsQ0FBQztJQUdELEtBQUssQ0FBQyxLQUFLLENBQWMsS0FBSztRQUMxQixJQUFJLENBQUMsR0F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FBQUcsQ0FBQyxVQUFVLENBQUM7SUFDRCxtQkFBQSxpQkFBTyxFQUFFLENBQUE7Ozs7Z0RBRXZCO0FBR0Q7SUFEQyxhQUFHLENBQUMsV0FBVyxDQUFDO0lBQ0QsbUJBQUEsa0JBQVEsRUFBRSxDQUFBOzs7O2lEQUV6QjtBQUdEO0lBREMsYUFBRyxDQUFDLFVBQVUsQ0FBQztJQUNELG1CQUFBLGlCQUFPLEVBQUUsQ0FBQTs7OztnREFFdkI7QUFHRDtJQURDLGFBQUcsQ0FBQyxVQUFVLENBQUM7SUFDRCxtQkFBQSxpQkFBTyxFQUFFLENBQUE7Ozs7Z0RBRXZCO0FBR0Q7SUFEQyxjQUFJLENBQUMsT0FBTyxDQUFDO0lBQ0YsbUJBQUEsY0FBSSxFQUFFLENBQUE7Ozs7NkNBRWpCO0FBeENDLGlCQUFpQjtJQUR0QixvQkFBVSxDQUFDLFNBQVMsQ0FBQztHQUNoQixpQkFBaUIsQ0F5Q3RCO0FBR0Qsa0JBQWUsaUJBQWlCLENBQUMifQ== -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/controller_options.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let MiddlewareAController = class ControllerOptions extends egg_1.BaseContextClass { 7 | async foo() { 8 | return 'foo'; 9 | } 10 | async bar() { 11 | return 'bar'; 12 | } 13 | }; 14 | tslib_1.__decorate([ 15 | egg_pig_1.Get('foo', { middleware: ['logb'] }), 16 | tslib_1.__metadata("design:type", Function), 17 | tslib_1.__metadata("design:paramtypes", []), 18 | tslib_1.__metadata("design:returntype", Promise) 19 | ], MiddlewareAController.prototype, "foo", null); 20 | tslib_1.__decorate([ 21 | egg_pig_1.Get('bar'), 22 | tslib_1.__metadata("design:type", Function), 23 | tslib_1.__metadata("design:paramtypes", []), 24 | tslib_1.__metadata("design:returntype", Promise) 25 | ], MiddlewareAController.prototype, "bar", null); 26 | MiddlewareAController = tslib_1.__decorate([ 27 | egg_pig_1.Controller('controller_options', { middleware: ['loga'] }) 28 | ], MiddlewareAController); 29 | exports.default = MiddlewareAController; -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/dep/dep.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../../") 6 | let DepController = class DepController extends egg_1.BaseContextClass { 7 | async query(query) { 8 | this.ctx.body = query.id; 9 | } 10 | }; 11 | tslib_1.__decorate([ 12 | egg_pig_1.Get('/query'), 13 | tslib_1.__param(0, egg_pig_1.Query()), 14 | tslib_1.__metadata("design:type", Function), 15 | tslib_1.__metadata("design:paramtypes", [Object]), 16 | tslib_1.__metadata("design:returntype", Promise) 17 | ], DepController.prototype, "query", null); 18 | DepController = tslib_1.__decorate([ 19 | egg_pig_1.Controller('dep') 20 | ], DepController); 21 | exports.default = DepController; 22 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZGVwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUN2QyxxQ0FBZ0Q7QUFLaEQsSUFBTSxhQUFhLEdBQW5CLG1CQUFvQixTQUFRLHNCQUFnQjtJQUd4QyxLQUFLLENBQUMsS0FBSyxDQUFVLEtBQUs7UUFDdEIsSUFBSSxDQUFDLEdBQUcsQ0FBQyxJQUFJLEdBQUcsS0FBSyxDQUFDLEVBQUUsQ0FBQztJQUM3QixDQUFDO0NBRUosQ0FBQTtBQUpHO0lBREMsYUFBRyxDQUFDLFFBQVEsQ0FBQztJQUNELG1CQUFBLGVBQUssRUFBRSxDQUFBOzs7OzBDQUVuQjtBQUxDLGFBQWE7SUFEbEIsb0JBQVUsQ0FBQyxLQUFLLENBQUM7R0FDWixhQUFhLENBT2xCO0FBR0Qsa0JBQWUsYUFBYSxDQUFDIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/dep/innerdep/dep01.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../../../") 6 | let InnerDepController = class InnerDepController extends egg_1.BaseContextClass { 7 | async query(query) { 8 | this.ctx.body = query; 9 | } 10 | }; 11 | tslib_1.__decorate([ 12 | egg_pig_1.Get('/query'), 13 | tslib_1.__param(0, egg_pig_1.Query()), 14 | tslib_1.__metadata("design:type", Function), 15 | tslib_1.__metadata("design:paramtypes", [Object]), 16 | tslib_1.__metadata("design:returntype", Promise) 17 | ], InnerDepController.prototype, "query", null); 18 | InnerDepController = tslib_1.__decorate([ 19 | egg_pig_1.Controller('innerdep') 20 | ], InnerDepController); 21 | exports.default = InnerDepController; 22 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVwMDEuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJkZXAwMS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSw2QkFBdUM7QUFDdkMscUNBQWdEO0FBS2hELElBQU0sa0JBQWtCLEdBQXhCLHdCQUF5QixTQUFRLHNCQUFnQjtJQUc3QyxLQUFLLENBQUMsS0FBSyxDQUFVLEtBQUs7UUFDdEIsSUFBSSxDQUFDLEdBQUcsQ0FBQyxJQUFJLEdBQUcsS0FBSyxDQUFDO0lBQzFCLENBQUM7Q0FFSixDQUFBO0FBSkc7SUFEQyxhQUFHLENBQUMsUUFBUSxDQUFDO0lBQ0QsbUJBQUEsZUFBSyxFQUFFLENBQUE7Ozs7K0NBRW5CO0FBTEMsa0JBQWtCO0lBRHZCLG9CQUFVLENBQUMsVUFBVSxDQUFDO0dBQ2pCLGtCQUFrQixDQU92QjtBQUdELGtCQUFlLGtCQUFrQixDQUFDIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/exception.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let ExceptionController = class ExceptionController extends egg_1.BaseContextClass { 7 | async forbiden() { 8 | throw new egg_pig_1.ForbiddenException(); 9 | } 10 | async bad() { 11 | throw new egg_pig_1.BadRequestException(); 12 | } 13 | async unauthorized() { 14 | throw new egg_pig_1.UnauthorizedException(); 15 | } 16 | async nofound() { 17 | throw new egg_pig_1.NotFoundException(); 18 | } 19 | async notaccept() { 20 | throw new egg_pig_1.NotAcceptableException(); 21 | } 22 | async timeout() { 23 | throw new egg_pig_1.RequestTimeoutException(); 24 | } 25 | async conflict() { 26 | throw new egg_pig_1.ConflictException(); 27 | } 28 | async playlod() { 29 | throw new egg_pig_1.GoneException(); 30 | } 31 | async payload() { 32 | throw new egg_pig_1.PayloadTooLargeException(); 33 | } 34 | async unsupport() { 35 | throw new egg_pig_1.UnsupportedMediaTypeException(); 36 | } 37 | async unprocess() { 38 | throw new egg_pig_1.UnprocessableEntityException(); 39 | } 40 | async internal() { 41 | throw new egg_pig_1.InternalServerErrorException(); 42 | } 43 | async notimplement() { 44 | throw new egg_pig_1.NotImplementedException(); 45 | } 46 | async badtateway() { 47 | throw new egg_pig_1.BadGatewayException(); 48 | } 49 | async serviceun() { 50 | throw new egg_pig_1.ServiceUnavailableException(); 51 | } 52 | async gatewaytimeout() { 53 | throw new egg_pig_1.GatewayTimeoutException(); 54 | } 55 | }; 56 | tslib_1.__decorate([ 57 | egg_pig_1.Get('forbiden'), 58 | tslib_1.__metadata("design:type", Function), 59 | tslib_1.__metadata("design:paramtypes", []), 60 | tslib_1.__metadata("design:returntype", Promise) 61 | ], ExceptionController.prototype, "forbiden", null); 62 | tslib_1.__decorate([ 63 | egg_pig_1.Get('badrequest'), 64 | tslib_1.__metadata("design:type", Function), 65 | tslib_1.__metadata("design:paramtypes", []), 66 | tslib_1.__metadata("design:returntype", Promise) 67 | ], ExceptionController.prototype, "bad", null); 68 | tslib_1.__decorate([ 69 | egg_pig_1.Get('unauthorized'), 70 | tslib_1.__metadata("design:type", Function), 71 | tslib_1.__metadata("design:paramtypes", []), 72 | tslib_1.__metadata("design:returntype", Promise) 73 | ], ExceptionController.prototype, "unauthorized", null); 74 | tslib_1.__decorate([ 75 | egg_pig_1.Get('notfound'), 76 | tslib_1.__metadata("design:type", Function), 77 | tslib_1.__metadata("design:paramtypes", []), 78 | tslib_1.__metadata("design:returntype", Promise) 79 | ], ExceptionController.prototype, "nofound", null); 80 | tslib_1.__decorate([ 81 | egg_pig_1.Get('notacceptable'), 82 | tslib_1.__metadata("design:type", Function), 83 | tslib_1.__metadata("design:paramtypes", []), 84 | tslib_1.__metadata("design:returntype", Promise) 85 | ], ExceptionController.prototype, "notaccept", null); 86 | tslib_1.__decorate([ 87 | egg_pig_1.Get('timeout'), 88 | tslib_1.__metadata("design:type", Function), 89 | tslib_1.__metadata("design:paramtypes", []), 90 | tslib_1.__metadata("design:returntype", Promise) 91 | ], ExceptionController.prototype, "timeout", null); 92 | tslib_1.__decorate([ 93 | egg_pig_1.Get('conflict'), 94 | tslib_1.__metadata("design:type", Function), 95 | tslib_1.__metadata("design:paramtypes", []), 96 | tslib_1.__metadata("design:returntype", Promise) 97 | ], ExceptionController.prototype, "conflict", null); 98 | tslib_1.__decorate([ 99 | egg_pig_1.Get('gone'), 100 | tslib_1.__metadata("design:type", Function), 101 | tslib_1.__metadata("design:paramtypes", []), 102 | tslib_1.__metadata("design:returntype", Promise) 103 | ], ExceptionController.prototype, "playlod", null); 104 | tslib_1.__decorate([ 105 | egg_pig_1.Get('payload'), 106 | tslib_1.__metadata("design:type", Function), 107 | tslib_1.__metadata("design:paramtypes", []), 108 | tslib_1.__metadata("design:returntype", Promise) 109 | ], ExceptionController.prototype, "payload", null); 110 | tslib_1.__decorate([ 111 | egg_pig_1.Get('unsupport'), 112 | tslib_1.__metadata("design:type", Function), 113 | tslib_1.__metadata("design:paramtypes", []), 114 | tslib_1.__metadata("design:returntype", Promise) 115 | ], ExceptionController.prototype, "unsupport", null); 116 | tslib_1.__decorate([ 117 | egg_pig_1.Get('unprocess'), 118 | tslib_1.__metadata("design:type", Function), 119 | tslib_1.__metadata("design:paramtypes", []), 120 | tslib_1.__metadata("design:returntype", Promise) 121 | ], ExceptionController.prototype, "unprocess", null); 122 | tslib_1.__decorate([ 123 | egg_pig_1.Get('internal'), 124 | tslib_1.__metadata("design:type", Function), 125 | tslib_1.__metadata("design:paramtypes", []), 126 | tslib_1.__metadata("design:returntype", Promise) 127 | ], ExceptionController.prototype, "internal", null); 128 | tslib_1.__decorate([ 129 | egg_pig_1.Get('notimplement'), 130 | tslib_1.__metadata("design:type", Function), 131 | tslib_1.__metadata("design:paramtypes", []), 132 | tslib_1.__metadata("design:returntype", Promise) 133 | ], ExceptionController.prototype, "notimplement", null); 134 | tslib_1.__decorate([ 135 | egg_pig_1.Get('badgateway'), 136 | tslib_1.__metadata("design:type", Function), 137 | tslib_1.__metadata("design:paramtypes", []), 138 | tslib_1.__metadata("design:returntype", Promise) 139 | ], ExceptionController.prototype, "badtateway", null); 140 | tslib_1.__decorate([ 141 | egg_pig_1.Get('service'), 142 | tslib_1.__metadata("design:type", Function), 143 | tslib_1.__metadata("design:paramtypes", []), 144 | tslib_1.__metadata("design:returntype", Promise) 145 | ], ExceptionController.prototype, "serviceun", null); 146 | tslib_1.__decorate([ 147 | egg_pig_1.Get('gatewaytimeout'), 148 | tslib_1.__metadata("design:type", Function), 149 | tslib_1.__metadata("design:paramtypes", []), 150 | tslib_1.__metadata("design:returntype", Promise) 151 | ], ExceptionController.prototype, "gatewaytimeout", null); 152 | ExceptionController = tslib_1.__decorate([ 153 | egg_pig_1.Controller('exception') 154 | ], ExceptionController); 155 | exports.default = ExceptionController; 156 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXhjZXB0aW9uLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZXhjZXB0aW9uLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUN2QyxxQ0FBeWE7QUFHemEsSUFBcUIsbUJBQW1CLEdBQXhDLHlCQUF5QyxTQUFRLHNCQUFnQjtJQUc3RCxLQUFLLENBQUMsUUFBUTtRQUNWLE1BQU0sSUFBSSw0QkFBa0IsRUFBRSxDQUFBO0lBQ2xDLENBQUM7SUFHRCxLQUFLLENBQUMsR0FBRztRQUNMLE1BQU0sSUFBSSw2QkFBbUIsRUFBRSxDQUFBO0lBQ25DLENBQUM7SUFHRCxLQUFLLENBQUMsWUFBWTtRQUNkLE1BQU0sSUFBSSwrQkFBcUIsRUFBRSxDQUFBO0lBQ3JDLENBQUM7SUFHRCxLQUFLLENBQUMsT0FBTztRQUNULE1BQU0sSUFBSSwyQkFBaUIsRUFBRSxDQUFBO0lBQ2pDLENBQUM7SUFHRCxLQUFLLENBQUMsU0FBUztRQUNYLE1BQU0sSUFBSSxnQ0FBc0IsRUFBRSxDQUFBO0lBQ3RDLENBQUM7SUFHRCxLQUFLLENBQUMsT0FBTztRQUNULE1BQU0sSUFBSSxpQ0FBdUIsRUFBRSxDQUFBO0lBQ3ZDLENBQUM7SUFHRCxLQUFLLENBQUMsUUFBUTtRQUNWLE1BQU0sSUFBSSwyQkFBaUIsRUFBRSxDQUFDO0lBQ2xDLENBQUM7SUFHRCxLQUFLLENBQUMsT0FBTztRQUNULE1BQU0sSUFBSSx1QkFBYSxFQUFFLENBQUE7SUFDN0IsQ0FBQztJQUdELEtBQUssQ0FBQyxPQUFPO1FBQ1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FDLE1BQU0sQ0FBQzs7OztrREFHWDtBQUdEO0lBREMsYUFBRyxDQUFDLFNBQVMsQ0FBQzs7OztrREFHZDtBQUdEO0lBREMsYUFBRyxDQUFDLFdBQVcsQ0FBQzs7OztvREFHaEI7QUFHRDtJQURDLGFBQUcsQ0FBQyxXQUFXLENBQUM7Ozs7b0RBR2hCO0FBSUQ7SUFEQyxhQUFHLENBQUMsVUFBVSxDQUFDOzs7O21EQUdmO0FBS0Q7SUFEQyxhQUFHLENBQUMsY0FBYyxDQUFDOzs7O3VEQUduQjtBQUlEO0lBREMsYUFBRyxDQUFDLFlBQVksQ0FBQzs7OztxREFHakI7QUFHRDtJQURDLGFBQUcsQ0FBQyxTQUFTLENBQUM7Ozs7b0RBR2Q7QUFJRDtJQURDLGFBQUcsQ0FBQyxnQkFBZ0IsQ0FBQzs7Ozt5REFHckI7QUFyRmdCLG1CQUFtQjtJQUR2QyxvQkFBVSxDQUFDLFdBQVcsQ0FBQztHQUNILG1CQUFtQixDQXdGdkM7a0JBeEZvQixtQkFBbUIifQ== -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/exportcommon.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | const egg_1 = require("egg"); 13 | const egg_pig_1 = require("../../../../../../"); 14 | let PriorityAController = class PriorityAController { 15 | constructor(ctx, app, config, service) { 16 | this.ctx = ctx; 17 | this.app = app; 18 | this.config = config; 19 | this.service = service; 20 | } 21 | async foo() { 22 | return 'hello'; 23 | } 24 | }; 25 | __decorate([ 26 | egg_pig_1.Get("/test"), 27 | __metadata("design:type", Function), 28 | __metadata("design:paramtypes", []), 29 | __metadata("design:returntype", Promise) 30 | ], PriorityAController.prototype, "foo", null); 31 | PriorityAController = __decorate([ 32 | egg_pig_1.Priority(1), 33 | egg_pig_1.Controller('exports'), 34 | __metadata("design:paramtypes", [Object, egg_1.Application, Object, Object]) 35 | ], PriorityAController); 36 | exports.PriorityAController = PriorityAController; 37 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHJpb3JpdHlBLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vYXBwL2NvbnRyb2xsZXIvcHJpb3JpdHlBLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7O0FBQUEsNkJBQW1FO0FBQ25FLHFDQUFvRDtBQUtwRCxJQUFhLG1CQUFtQixHQUFoQyxNQUFhLG1CQUFtQjtJQUU5QixZQUNVLEdBQVksRUFDWixHQUFnQixFQUNoQixNQUFvQixFQUNwQixPQUFpQjtRQUhqQixRQUFHLEdBQUgsR0FBRyxDQUFTO1FBQ1osUUFBRyxHQUFILEdBQUcsQ0FBYTtRQUNoQixXQUFNLEdBQU4sTUFBTSxDQUFjO1FBQ3BCLFlBQU8sR0FBUCxPQUFPLENBQVU7SUFDdkIsQ0FBQztJQUdMLEtBQUssQ0FBQyxHQUFHO1FBQ1AsT0FBTyxPQUFPLENBQUM7SUFDakIsQ0FBQztDQUdGLENBQUE7QUFMQztJQURDLGFBQUcsQ0FBQyxPQUFPLENBQUM7Ozs7OENBR1o7QUFaVSxtQkFBbUI7SUFGL0Isa0JBQVEsQ0FBQyxDQUFDLENBQUM7SUFDWCxvQkFBVSxDQUFDLFFBQVEsQ0FBQzs2Q0FLSixpQkFBVztHQUpmLG1CQUFtQixDQWUvQjtBQWZZLGtEQUFtQiJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/filter.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | const egg_pig_2 = require("../../../../../../"); 7 | let AExceptionFilter = class AExceptionFilter extends egg_pig_2.ExceptionFilter { 8 | catch(exception) { 9 | this.ctx.status = egg_pig_1.HttpStatus.FORBIDDEN; 10 | this.ctx.body = { 11 | statusCode: exception.getStatus(), 12 | path: this.ctx.req.url 13 | }; 14 | } 15 | }; 16 | AExceptionFilter = tslib_1.__decorate([ 17 | egg_pig_2.Catch(egg_pig_1.HttpException) 18 | ], AExceptionFilter); 19 | class ForbiddenException extends egg_pig_1.HttpException { 20 | constructor() { 21 | super('Forbidden', egg_pig_1.HttpStatus.FORBIDDEN); 22 | } 23 | } 24 | let FilterController = class FilterController extends egg_1.BaseContextClass { 25 | async foo() { 26 | throw new egg_pig_1.HttpException({ 27 | error: 'error', 28 | }, 500); 29 | } 30 | async bar() { 31 | throw new egg_pig_1.HttpException('Forbidden', egg_pig_1.HttpStatus.FORBIDDEN); 32 | } 33 | async foobar() { 34 | throw new egg_pig_1.HttpException({ 35 | status: egg_pig_1.HttpStatus.FORBIDDEN, 36 | error: 'This is a custom message', 37 | }, 403); 38 | } 39 | async forbiden() { 40 | throw new ForbiddenException(); 41 | } 42 | }; 43 | tslib_1.__decorate([ 44 | egg_pig_2.Get('common'), 45 | tslib_1.__metadata("design:type", Function), 46 | tslib_1.__metadata("design:paramtypes", []), 47 | tslib_1.__metadata("design:returntype", Promise) 48 | ], FilterController.prototype, "foo", null); 49 | tslib_1.__decorate([ 50 | egg_pig_2.Get('httpexception'), 51 | tslib_1.__metadata("design:type", Function), 52 | tslib_1.__metadata("design:paramtypes", []), 53 | tslib_1.__metadata("design:returntype", Promise) 54 | ], FilterController.prototype, "bar", null); 55 | tslib_1.__decorate([ 56 | egg_pig_2.Get('another'), 57 | egg_pig_2.UseFilters(AExceptionFilter), 58 | tslib_1.__metadata("design:type", Function), 59 | tslib_1.__metadata("design:paramtypes", []), 60 | tslib_1.__metadata("design:returntype", Promise) 61 | ], FilterController.prototype, "foobar", null); 62 | tslib_1.__decorate([ 63 | egg_pig_2.Get('forbiden'), 64 | tslib_1.__metadata("design:type", Function), 65 | tslib_1.__metadata("design:paramtypes", []), 66 | tslib_1.__metadata("design:returntype", Promise) 67 | ], FilterController.prototype, "forbiden", null); 68 | FilterController = tslib_1.__decorate([ 69 | egg_pig_2.Controller('filter') 70 | ], FilterController); 71 | exports.default = FilterController; 72 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZmlsdGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZmlsdGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUV2QyxxQ0FBb0Q7QUFFcEQscUNBTWlCO0FBSWpCLElBQU0sZ0JBQWdCLEdBQXRCLHNCQUF1QixTQUFRLHlCQUFlO0lBQzFDLEtBQUssQ0FBQyxTQUFTLEVBQUUsR0FBRztRQUNoQixHQUFHLENBQUMsTUFBTSxHQUFHLG9CQUFVLENBQUMsU0FBUyxDQUFDO1FBQ2xDLEdBQUcsQ0FBQyxJQUFJLEdBQUc7WUFDUCxVQUFVLEVBQUUsU0FBUyxDQUFDLFNBQVMsRUFBRTtZQUNqQyxTQUFTLEVBQUUsSUFBSSxJQUFJLEVBQUUsQ0FBQyxXQUFXLEVBQUU7WUFDbkMsSUFBSSxFQUFFLEdBQUcsQ0FBQyxHQUFHLENBQUMsR0FBRztTQUNwQixDQUFBO0lBQ0wsQ0FB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BQWdCO0lBRHBDLG9CQUFVLENBQUMsUUFBUSxDQUFDO0dBQ0EsZ0JBQWdCLENBMkJwQztrQkEzQm9CLGdCQUFnQiJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/global.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let GlobalController = class GlobalController extends egg_1.BaseContextClass { 7 | async foo() { 8 | return 'ok'; 9 | } 10 | async bar(id) { 11 | return id; 12 | } 13 | async xxx() { 14 | return 'ok'; 15 | } 16 | async yyy() { 17 | throw new egg_pig_1.HttpException('exception', egg_pig_1.HttpStatus.BAD_REQUEST); 18 | } 19 | }; 20 | tslib_1.__decorate([ 21 | egg_pig_1.Get('guard'), 22 | tslib_1.__metadata("design:type", Function), 23 | tslib_1.__metadata("design:paramtypes", []), 24 | tslib_1.__metadata("design:returntype", Promise) 25 | ], GlobalController.prototype, "foo", null); 26 | tslib_1.__decorate([ 27 | egg_pig_1.Get('pipe'), 28 | tslib_1.__param(0, egg_pig_1.Query('id')), 29 | tslib_1.__metadata("design:type", Function), 30 | tslib_1.__metadata("design:paramtypes", [Object]), 31 | tslib_1.__metadata("design:returntype", Promise) 32 | ], GlobalController.prototype, "bar", null); 33 | tslib_1.__decorate([ 34 | egg_pig_1.Get('interceptor'), 35 | tslib_1.__metadata("design:type", Function), 36 | tslib_1.__metadata("design:paramtypes", []), 37 | tslib_1.__metadata("design:returntype", Promise) 38 | ], GlobalController.prototype, "xxx", null); 39 | tslib_1.__decorate([ 40 | egg_pig_1.Get('filter'), 41 | tslib_1.__metadata("design:type", Function), 42 | tslib_1.__metadata("design:paramtypes", []), 43 | tslib_1.__metadata("design:returntype", Promise) 44 | ], GlobalController.prototype, "yyy", null); 45 | GlobalController = tslib_1.__decorate([ 46 | egg_pig_1.Controller('global') 47 | ], GlobalController); 48 | exports.default = GlobalController; 49 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFsLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZ2xvYmFsLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUN2QyxxQ0FBNEU7QUFHNUUsSUFBcUIsZ0JBQWdCLEdBQXJDLHNCQUFzQyxTQUFRLHNCQUFnQjtJQUcxRCxLQUFLLENBQUMsR0FBRztRQUNMLE9BQU8sSUFBSSxDQUFDO0lBQ2hCLENBQUM7SUFHRCxLQUFLLENBQUMsR0FBRyxDQUFjLEVBQUU7UUFDckIsT0FBTyxFQUFFLENBQUM7SUFDZCxDQUFDO0lBR0QsS0FBSyxDQUFDLEdBQUc7UUFDTCxPQUFPLElBQUksQ0FBQztJQUNoQixDQUFDO0lBR0QsS0FBSyxDQUFDLEdBQUc7UUFDTCxNQUFNLElBQUksdUJBQWEsQ0FBQyxXQUFXLEVBQUUsb0JBQVUsQ0FBQyxXQUFXLENBQUMsQ0FBQztJQUNqRSxDQUFDO0NBQ0osQ0FBQTtBQWxCRztJQURDLGFBQUcsQ0FBQyxPQUFPLENBQUM7Ozs7MkNBR1o7QUFHRDtJQURDLGFBQUcsQ0FBQyxNQUFNLENBQUM7SUFDRCxtQkFBQSxlQUFLLENBQUMsSUFBSSxDQUFDLENBQUE7Ozs7MkNBRXJCO0FBR0Q7SUFEQyxhQUFHLENBQUMsYUFBYSxDQUFDOzs7OzJDQUdsQjtBQUdEO0lBREMsYUFBRyxDQUFDLFFBQVEsQ0FBQzs7OzsyQ0FHYjtBQXBCZ0IsZ0JBQWdCO0lBRHBDLG9CQUFVLENBQUMsUUFBUSxDQUFDO0dBQ0EsZ0JBQWdCLENBcUJwQztrQkFyQm9CLGdCQUFnQiJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/guard.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let AGuard = class AGuard { 7 | async canActivate(context) { 8 | const { getClass, getHandler } = context 9 | if (this.ctx.req.url === '/guard/forbiden') 10 | return false; 11 | return { parent: getClass(), handler: getHandler() }; 12 | } 13 | }; 14 | AGuard = tslib_1.__decorate([ 15 | egg_pig_1.Injectable() 16 | ], AGuard); 17 | let BGuard = class BGuard { 18 | canActivate(context) { 19 | const { getClass, getHandler } = context 20 | if (/guard.*?/.test(this.ctx.req.url)){ 21 | return { parent: getClass(), handler: getHandler() }; 22 | } 23 | } 24 | }; 25 | BGuard = tslib_1.__decorate([ 26 | egg_pig_1.Injectable() 27 | ], BGuard); 28 | let GuardController = class GuardController extends egg_1.BaseContextClass { 29 | async index(query) { 30 | this.ctx.body = query; 31 | } 32 | async body() { 33 | this.ctx.body = '403'; 34 | } 35 | async nothing() { 36 | this.ctx.body = 'nothing'; 37 | } 38 | }; 39 | tslib_1.__decorate([ 40 | egg_pig_1.Get('/'), 41 | egg_pig_1.UseGuards(BGuard), 42 | tslib_1.__param(0, egg_pig_1.Query()), 43 | tslib_1.__metadata("design:type", Function), 44 | tslib_1.__metadata("design:paramtypes", [Object]), 45 | tslib_1.__metadata("design:returntype", Promise) 46 | ], GuardController.prototype, "index", null); 47 | tslib_1.__decorate([ 48 | egg_pig_1.Get('forbiden'), 49 | tslib_1.__metadata("design:type", Function), 50 | tslib_1.__metadata("design:paramtypes", []), 51 | tslib_1.__metadata("design:returntype", Promise) 52 | ], GuardController.prototype, "body", null); 53 | tslib_1.__decorate([ 54 | egg_pig_1.Get('/nothing'), 55 | tslib_1.__metadata("design:type", Function), 56 | tslib_1.__metadata("design:paramtypes", []), 57 | tslib_1.__metadata("design:returntype", Promise) 58 | ], GuardController.prototype, "nothing", null); 59 | GuardController = tslib_1.__decorate([ 60 | egg_pig_1.Controller('guard'), 61 | egg_pig_1.UseGuards(AGuard) 62 | ], GuardController); 63 | exports.default = GuardController; 64 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ3VhcmQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJndWFyZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSw2QkFBdUM7QUFDdkMscUNBQW9FO0FBR3BFLElBQU0sTUFBTSxHQUFaO0lBQ0ksS0FBSyxDQUFDLFdBQVcsQ0FBQyxHQUFHLEVBQUUsT0FBTztRQUMxQixNQUFNLEVBQUUsTUFBTSxFQUFFLE9BQU8sRUFBRSxHQUFHLE9BQU8sQ0FBQztRQUNwQyxJQUFHLEdBQUcsQ0FBQyxHQUFHLEtBQUssaUJBQWlCO1lBQUUsT0FBTyxLQUFLLENBQUM7UUFDL0MsT0FBTyxFQUFDLE1BQU0sRUFBRSxPQUFPLEVBQUMsQ0FBQztJQUM3QixDQUFDO0NBQ0osQ0FBQTtBQU5LLE1BQU07SUFEWCxlQUFLLEVBQUU7R0FDRixNQUFNLENBTVg7QUFHRCxJQUFNLE1BQU0sR0FBWjtJQUNJLFdBQVcsQ0FBQyxHQUFHLEVBQUUsT0FBTztRQUNwQixNQUFNLEVBQUUsTUFBTSxFQUFFLE9BQU8sRUFBRSxHQUFHLE9BQU8sQ0FBQztRQUNwQyxJQUFJLEdBQUcsQ0FBQyxHQUFHLEtBQUssUUFBUSxFQUFDO1lBQ3JCLE9BQU8sRUFBQyxNQUFNLEVBQUUsT0FBTyxFQUFDLENBQUM7U0FDNUI7SUFDTCxDQUFDO0NBQ0osQ0FBQTtBQVBLLE1BQU07SUFEWCxlQUFLLEVBQUU7R0FDRixNQUFNLENBT1g7QUFJRCxJQUFNLE1BQU0sR0FBWjtJQUNJLFVBQVUsQ0FBQyxDQUFDLEVBQUUsRUFBRTtRQUNaLE9BQU8sS0FBSyxDQUFDO0lBQ2pCLENBQUM7Q0FDSixDQUFBO0FBSkssTUFBTTtJQURYLGVBQUssRUFBRTtHQUNGLE1BQU0sQ0FJWDtBQUlELElBQU0sZUFBZSxHQUFyQixxQkFBc0IsU0FBUSxzQkFBZ0I7SUFJMUMsS0FBSyxDQUFDLEtBQUssQ0FBVSxLQUFLO1FBQ3RCLElBQUksQ0FBQyxHQUFHLENBQUMsSUFBSSxHQUFHLEtBQUssQ0FBQztJQUMxQixDQUFDO0lBR0QsS0FBSyxDQUFDLElBQUk7UUFDTixJQUFJLENBQUMsR0FBRyxDQUFDLElBQUksR0FBRyxLQUFLLENBQUM7SUFDMUIsQ0FBQztJQUlELEtBQUssQ0FBQyxPQUFPO1FBQ1QsSUFBSSxDQUFDLEdBQUcsQ0FBQyxJQUFJLEdBQUcsU0FBUyxDQUFDO0lBQzlCLENBQUM7Q0FDSixDQUFBO0FBZEc7SUFGQyxhQUFHLENBQUMsR0FBRyxDQUFDO0lBQ1IsbUJBQVMsQ0FBQyxNQUFNLENBQUM7SUFDTCxtQkFBQSxlQUFLLEVBQUUsQ0FBQTs7Ozs0Q0FFbkI7QUFHRDtJQURDLGFBQUcsQ0FBQyxVQUFVLENBQUM7Ozs7MkNBR2Y7QUFJRDtJQUZDLG1CQUFTLENBQUMsTUFBTSxDQUFDO0lBQ2pCLGFBQUcsQ0FBQyxVQUFVLENBQUM7Ozs7OENBR2Y7QUFqQkMsZUFBZTtJQUZwQixvQkFBVSxDQUFDLE9BQU8sQ0FBQztJQUNuQixtQkFBUyxDQUFDLE1BQU0sQ0FBQztHQUNaLGVBQWUsQ0FrQnBCO0FBR0Qsa0JBQWUsZUFBZSxDQUFDIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/header.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let HeaderController = class HeaderController extends egg_1.BaseContextClass { 7 | async foo() { 8 | return 'ok'; 9 | } 10 | async bar() { 11 | return 'ok'; 12 | } 13 | }; 14 | tslib_1.__decorate([ 15 | egg_pig_1.Get('etag/'), 16 | egg_pig_1.Header('ETag', '123'), 17 | tslib_1.__metadata("design:type", Function), 18 | tslib_1.__metadata("design:paramtypes", []), 19 | tslib_1.__metadata("design:returntype", Promise) 20 | ], HeaderController.prototype, "foo", null); 21 | tslib_1.__decorate([ 22 | egg_pig_1.Get('/other/'), 23 | egg_pig_1.Header({ 24 | 'Etag': '1234', 25 | 'Last-Modified': '2018-9-1', 26 | }), 27 | tslib_1.__metadata("design:type", Function), 28 | tslib_1.__metadata("design:paramtypes", []), 29 | tslib_1.__metadata("design:returntype", Promise) 30 | ], HeaderController.prototype, "bar", null); 31 | HeaderController = tslib_1.__decorate([ 32 | egg_pig_1.Controller('/header/') 33 | ], HeaderController); 34 | exports.default = HeaderController; 35 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGVhZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiaGVhZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUN2QyxxQ0FBaUQ7QUFHakQsSUFBcUIsZ0JBQWdCLEdBQXJDLHNCQUFzQyxTQUFRLHNCQUFnQjtJQUkxRCxLQUFLLENBQUMsR0FBRztRQUNMLE9BQU8sSUFBSSxDQUFDO0lBQ2hCLENBQUM7SUFPRCxLQUFLLENBQUMsR0FBRztRQUNMLE9BQU8sSUFBSSxDQUFDO0lBQ2hCLENBQUM7Q0FDSixDQUFBO0FBWkc7SUFGQyxhQUFHLENBQUMsTUFBTSxDQUFDO0lBQ1gsZ0JBQU0sQ0FBQyxNQUFNLEVBQUMsS0FBSyxDQUFDOzs7OzJDQUdwQjtBQU9EO0lBTEMsYUFBRyxDQUFDLE9BQU8sQ0FBQztJQUNaLGdCQUFNLENBQUM7UUFDSixNQUFNLEVBQUUsTUFBTTtRQUNkLGVBQWUsRUFBRSxJQUFJLElBQUksRUFBRTtLQUM5QixDQUFDOzs7OzJDQUdEO0FBZmdCLGdCQUFnQjtJQURwQyxvQkFBVSxDQUFDLFFBQVEsQ0FBQztHQUNBLGdCQUFnQixDQWdCcEM7a0JBaEJvQixnQkFBZ0IifQ== -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/helper.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | const egg_pig_2 = require("../../../../../../"); 7 | const egg_pig_3 = require("../../../../../../"); 8 | let RoleGuard = class RoleGuard extends egg_pig_3.CanActivate { 9 | canActivate(context) { 10 | const handler = context.getHandler(); 11 | const admin = this.ctx.helper['reflector'].get('Role', handler); 12 | return admin[0] === 'admin' ? true : false; 13 | } 14 | }; 15 | RoleGuard = tslib_1.__decorate([ 16 | egg_pig_3.Injectable() 17 | ], RoleGuard); 18 | const Roles = (...args) => egg_pig_2.ReflectMetadata('Role', args); 19 | let HelperController = class HelperController extends egg_1.BaseContextClass { 20 | async foo() { 21 | return 'admin'; 22 | } 23 | }; 24 | tslib_1.__decorate([ 25 | egg_pig_1.Get(), 26 | Roles('admin'), 27 | tslib_1.__metadata("design:type", Function), 28 | tslib_1.__metadata("design:paramtypes", []), 29 | tslib_1.__metadata("design:returntype", Promise) 30 | ], HelperController.prototype, "foo", null); 31 | HelperController = tslib_1.__decorate([ 32 | egg_pig_1.Controller('helper'), 33 | egg_pig_1.UseGuards(RoleGuard) 34 | ], HelperController); 35 | exports.default = HelperController; 36 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGVscGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiaGVscGVyLnRzIl0sIm5hbW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------------------------------- /test/fixtures/apps/pigapp/app/controller/httpcode.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let HttpcodeController = class HttpcodeController extends egg_1.BaseContextClass { 7 | async foo() { 8 | return 'ok'; 9 | } 10 | async bar() { 11 | return 'ok'; 12 | } 13 | }; 14 | tslib_1.__decorate([ 15 | egg_pig_1.HttpCode(egg_pig_1.HttpStatus.NOT_FOUND), 16 | egg_pig_1.Get('get'), 17 | tslib_1.__metadata("design:type", Function), 18 | tslib_1.__metadata("design:paramtypes", []), 19 | tslib_1.__metadata("design:returntype", Promise) 20 | ], HttpcodeController.prototype, "foo", null); 21 | tslib_1.__decorate([ 22 | egg_pig_1.HttpCode(egg_pig_1.HttpStatus.BAD_REQUEST), 23 | egg_pig_1.Post('post'), 24 | tslib_1.__metadata("design:type", Function), 25 | tslib_1.__metadata("design:paramtypes", []), 26 | tslib_1.__metadata("design:returntype", Promise) 27 | ], HttpcodeController.prototype, "bar", null); 28 | HttpcodeController = tslib_1.__decorate([ 29 | egg_pig_1.Controller('httpcode') 30 | ], HttpcodeController); 31 | exports.default = HttpcodeController; 32 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaHR0cGNvZGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJodHRwY29kZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSw2QkFBdUM7QUFDdkMscUNBQXFFO0FBR3JFLElBQXFCLGtCQUFrQixHQUF2Qyx3QkFBd0MsU0FBUSxzQkFBZ0I7SUFJNUQsS0FBSyxDQUFDLEdBQUc7UUFDTCxPQUFPLElBQUksQ0FBQztJQUNoQixDQUFDO0lBSUQsS0FBSyxDQUFDLEdBQUc7UUFDTCxPQUFPLElBQUksQ0FBQztJQUNoQixDQUFDO0NBQ0osQ0FBQTtBQVRHO0lBRkMsa0JBQVEsQ0FBQyxvQkFBVSxDQUFDLFNBQVMsQ0FBQztJQUM5QixhQUFHLENBQUMsS0FBSyxDQUFDOzs7OzZDQUdWO0FBSUQ7SUFGQyxrQkFBUSxDQUFDLG9CQUFVLENBQUMsV0FBVyxDQUFDO0lBQ2hDLGNBQUksQ0FBQyxNQUFNLENBQUM7Ozs7NkNBR1o7QUFaZ0Isa0JBQWtCO0lBRHRDLG9CQUFVLENBQUMsVUFBVSxDQUFDO0dBQ0Ysa0JBQWtCLENBYXRDO2tCQWJvQixrQkFBa0IifQ== -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/httpverb.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let HttpVerbController = class HttpVerbController extends egg_1.BaseContextClass { 7 | async get() { 8 | this.ctx.body = 'get'; 9 | } 10 | async post() { 11 | this.ctx.body = 'post'; 12 | } 13 | async head() { 14 | this.ctx.body = 'head'; 15 | } 16 | async patch() { 17 | this.ctx.body = 'patch'; 18 | } 19 | async put() { 20 | this.ctx.body = 'put'; 21 | } 22 | async delete() { 23 | this.ctx.body = 'delete'; 24 | } 25 | async options() { 26 | this.ctx.body = 'options'; 27 | } 28 | }; 29 | tslib_1.__decorate([ 30 | egg_pig_1.Get('/get'), 31 | tslib_1.__metadata("design:type", Function), 32 | tslib_1.__metadata("design:paramtypes", []), 33 | tslib_1.__metadata("design:returntype", Promise) 34 | ], HttpVerbController.prototype, "get", null); 35 | tslib_1.__decorate([ 36 | egg_pig_1.Post('/post'), 37 | tslib_1.__metadata("design:type", Function), 38 | tslib_1.__metadata("design:paramtypes", []), 39 | tslib_1.__metadata("design:returntype", Promise) 40 | ], HttpVerbController.prototype, "post", null); 41 | tslib_1.__decorate([ 42 | egg_pig_1.Head('/head'), 43 | tslib_1.__metadata("design:type", Function), 44 | tslib_1.__metadata("design:paramtypes", []), 45 | tslib_1.__metadata("design:returntype", Promise) 46 | ], HttpVerbController.prototype, "head", null); 47 | tslib_1.__decorate([ 48 | egg_pig_1.Patch('/patch'), 49 | tslib_1.__metadata("design:type", Function), 50 | tslib_1.__metadata("design:paramtypes", []), 51 | tslib_1.__metadata("design:returntype", Promise) 52 | ], HttpVerbController.prototype, "patch", null); 53 | tslib_1.__decorate([ 54 | egg_pig_1.Put('/put'), 55 | tslib_1.__metadata("design:type", Function), 56 | tslib_1.__metadata("design:paramtypes", []), 57 | tslib_1.__metadata("design:returntype", Promise) 58 | ], HttpVerbController.prototype, "put", null); 59 | tslib_1.__decorate([ 60 | egg_pig_1.Delete('/delete'), 61 | tslib_1.__metadata("design:type", Function), 62 | tslib_1.__metadata("design:paramtypes", []), 63 | tslib_1.__metadata("design:returntype", Promise) 64 | ], HttpVerbController.prototype, "delete", null); 65 | tslib_1.__decorate([ 66 | egg_pig_1.Options('/options'), 67 | tslib_1.__metadata("design:type", Function), 68 | tslib_1.__metadata("design:paramtypes", []), 69 | tslib_1.__metadata("design:returntype", Promise) 70 | ], HttpVerbController.prototype, "options", null); 71 | HttpVerbController = tslib_1.__decorate([ 72 | egg_pig_1.Controller('verb') 73 | ], HttpVerbController); 74 | exports.default = HttpVerbController; 75 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaHR0cHZlcmIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJodHRwdmVyYi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSw2QkFBdUM7QUFDdkMscUNBQW1GO0FBSW5GLElBQU0sa0JBQWtCLEdBQXhCLHdCQUF5QixTQUFRLHNCQUFnQjtJQUU3QyxLQUFLLENBQUMsR0FBRztRQUNMLElBQUksQ0FBQyxHQUFHLENBQUMsSUFBSSxHQUFHLEtBQUssQ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0sQ0FBQztHQUNiLGtCQUFrQixDQTZCdkI7QUFHRCxrQkFBZSxrQkFBa0IsQ0FBQyJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/interceptot.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | const tap = require("rxjs/operators").tap; 7 | let AInterceptor = class AInterceptor { 8 | async intercept(context, stream$) { 9 | const { getClass, getHandler } = context 10 | this.ctx.req.query = { id: 1 }; 11 | return stream$.handle().pipe(tap(() => { console.log(getClass(), getHandler()) })); 12 | } 13 | }; 14 | AInterceptor = tslib_1.__decorate([ 15 | egg_pig_1.Injectable() 16 | ], AInterceptor); 17 | let BInterceptor = class BInterceptor { 18 | async intercept( _, stream$) { 19 | this.ctx.req.path = '/'; 20 | return stream$.handle().pipe(tap(() => { })); 21 | } 22 | }; 23 | BInterceptor = tslib_1.__decorate([ 24 | egg_pig_1.Injectable() 25 | ], BInterceptor); 26 | let InterceptorController = class InterceptorController extends egg_1.BaseContextClass { 27 | async index() { 28 | this.ctx.body = { 29 | query: this.ctx.req.query, 30 | path: this.ctx.req.path 31 | }; 32 | } 33 | async body() { 34 | this.ctx.body = this.ctx.req.query; 35 | } 36 | async bar() { 37 | this.ctx.body = this.ctx.req.path; 38 | } 39 | }; 40 | tslib_1.__decorate([ 41 | egg_pig_1.Get('/'), 42 | egg_pig_1.UseInterceptors(BInterceptor), 43 | tslib_1.__metadata("design:type", Function), 44 | tslib_1.__metadata("design:paramtypes", []), 45 | tslib_1.__metadata("design:returntype", Promise) 46 | ], InterceptorController.prototype, "index", null); 47 | tslib_1.__decorate([ 48 | egg_pig_1.Get('/body'), 49 | tslib_1.__metadata("design:type", Function), 50 | tslib_1.__metadata("design:paramtypes", []), 51 | tslib_1.__metadata("design:returntype", Promise) 52 | ], InterceptorController.prototype, "body", null); 53 | tslib_1.__decorate([ 54 | egg_pig_1.Get('/foo'), 55 | tslib_1.__metadata("design:type", Function), 56 | tslib_1.__metadata("design:paramtypes", []), 57 | tslib_1.__metadata("design:returntype", Promise) 58 | ], InterceptorController.prototype, "bar", null); 59 | InterceptorController = tslib_1.__decorate([ 60 | egg_pig_1.Controller('interceptor'), 61 | egg_pig_1.UseInterceptors(AInterceptor) 62 | ], InterceptorController); 63 | exports.default = InterceptorController; 64 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW50ZXJjZXB0b3QuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbnRlcmNlcHRvdC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSw2QkFBdUM7QUFDdkMscUNBQTBFO0FBQzFFLGdDQUE4QjtBQUc5QixJQUFNLFlBQVksR0FBbEI7SUFDSSxLQUFLLENBQUMsU0FBUyxDQUFDLEdBQUcsRUFBRSxPQUFPLEVBQUUsT0FBTztRQUNqQyxNQUFNLEVBQUUsTUFBTSxFQUFFLE9BQU8sRUFBRSxHQUFHLE9BQU8sQ0FBQztRQUNwQyxHQUFHLENBQUMsS0FBSyxHQUFHLEVBQUMsRUFBRSxFQUFDLENBQUMsRUFBQyxDQUFDO1FBQ25CLE9BQU8sT0FBTyxDQUFDLEVBQUUsQ0FDYixHQUFHLEVBQUUsR0FBRSxPQUFPLENBQUMsR0FBRyxDQUFDLE1BQU0sRUFBRSxPQUFPLENBQUMsQ0FBQSxDQUFBLENBQUMsQ0FDdkMsQ0FBQztJQUNOLENBQUM7Q0FDSixDQUFBO0FBUkssWUFBWTtJQURqQixxQkFBVyxFQUFFO0dBQ1IsWUFBWSxDQVFqQjtBQUdELElBQU0sWUFBWSxHQUFsQjtJQUNJLEtBQUssQ0FBQyxTQUFTLENBQUMsR0FBRyxFQUFFLENBQUMsRUFBRSxPQUFPO1FBQzNCLEdBQUcsQ0FBQyxJQUFJLE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7aURBR1o7QUFJRDtJQUZDLGFBQUcsQ0FBQyxNQUFNLENBQUM7SUFDWCx5QkFBZSxDQUFDLFlBQVksQ0FBQzs7OztnREFHN0I7QUFuQkMscUJBQXFCO0lBRjFCLG9CQUFVLENBQUMsYUFBYSxDQUFDO0lBQ3pCLHlCQUFlLENBQUMsWUFBWSxDQUFDO0dBQ3hCLHFCQUFxQixDQW9CMUI7QUFHRCxrQkFBZSxxQkFBcUIsQ0FBQyJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/middleware_a.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let MiddlewareAController = class MiddlewareAController extends egg_1.BaseContextClass { 7 | async foo() { 8 | return 'foo'; 9 | } 10 | async bar() { 11 | return 'bar'; 12 | } 13 | }; 14 | tslib_1.__decorate([ 15 | egg_pig_1.Get('foo', { middleware: ['loga'] }), 16 | tslib_1.__metadata("design:type", Function), 17 | tslib_1.__metadata("design:paramtypes", []), 18 | tslib_1.__metadata("design:returntype", Promise) 19 | ], MiddlewareAController.prototype, "foo", null); 20 | tslib_1.__decorate([ 21 | egg_pig_1.Get('bar'), 22 | tslib_1.__metadata("design:type", Function), 23 | tslib_1.__metadata("design:paramtypes", []), 24 | tslib_1.__metadata("design:returntype", Promise) 25 | ], MiddlewareAController.prototype, "bar", null); 26 | MiddlewareAController = tslib_1.__decorate([ 27 | egg_pig_1.Controller('middleware_a') 28 | ], MiddlewareAController); 29 | exports.default = MiddlewareAController; 30 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWlkZGxld2FyZV9hLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsibWlkZGxld2FyZV9hLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUN2QyxxQ0FBMEM7QUFHMUMsSUFBcUIscUJBQXFCLEdBQTFDLDJCQUEyQyxTQUFRLHNCQUFnQjtJQUcvRCxLQUFLLENBQUMsR0FBRztRQUNMLE9BQU8sS0FBSyxDQUFDO0lBQ2pCLENBQUM7SUFHRCxLQUFLLENBQUMsR0FBRztRQUNMLE9BQU8sS0FBSyxDQUFDO0lBQ2pCLENBQUM7Q0FHSixDQUFBO0FBVkc7SUFEQyxhQUFHLENBQUMsS0FBSyxDQUFDOzs7O2dEQUdWO0FBR0Q7SUFEQyxhQUFHLENBQUMsS0FBSyxDQUFDOzs7O2dEQUdWO0FBVmdCLHFCQUFxQjtJQUR6QyxvQkFBVSxDQUFDLGNBQWMsQ0FBQztHQUNOLHFCQUFxQixDQWF6QztrQkFib0IscUJBQXFCIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/middleware_b.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let MiddlewareAController = class MiddlewareAController extends egg_1.BaseContextClass { 7 | async foo() { 8 | return 'foo'; 9 | } 10 | async bar() { 11 | return 'bar'; 12 | } 13 | }; 14 | tslib_1.__decorate([ 15 | egg_pig_1.Get('/foo/'), 16 | tslib_1.__metadata("design:type", Function), 17 | tslib_1.__metadata("design:paramtypes", []), 18 | tslib_1.__metadata("design:returntype", Promise) 19 | ], MiddlewareAController.prototype, "foo", null); 20 | tslib_1.__decorate([ 21 | egg_pig_1.Get('bar/'), 22 | tslib_1.__metadata("design:type", Function), 23 | tslib_1.__metadata("design:paramtypes", []), 24 | tslib_1.__metadata("design:returntype", Promise) 25 | ], MiddlewareAController.prototype, "bar", null); 26 | MiddlewareAController = tslib_1.__decorate([ 27 | egg_pig_1.Controller('/middleware_b/') 28 | ], MiddlewareAController); 29 | exports.default = MiddlewareAController; 30 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWlkZGxld2FyZV9iLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsibWlkZGxld2FyZV9iLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUN2QyxxQ0FBMEM7QUFHMUMsSUFBcUIscUJBQXFCLEdBQTFDLDJCQUEyQyxTQUFRLHNCQUFnQjtJQUcvRCxLQUFLLENBQUMsR0FBRztRQUNMLE9BQU8sS0FBSyxDQUFDO0lBQ2pCLENBQUM7SUFHRCxLQUFLLENBQUMsR0FBRztRQUNMLE9BQU8sS0FBSyxDQUFDO0lBQ2pCLENBQUM7Q0FHSixDQUFBO0FBVkc7SUFEQyxhQUFHLENBQUMsS0FBSyxDQUFDOzs7O2dEQUdWO0FBR0Q7SUFEQyxhQUFHLENBQUMsS0FBSyxDQUFDOzs7O2dEQUdWO0FBVmdCLHFCQUFxQjtJQUR6QyxvQkFBVSxDQUFDLGNBQWMsQ0FBQztHQUNOLHFCQUFxQixDQWF6QztrQkFib0IscUJBQXFCIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/middleware_resource.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | 7 | let MiddlewareResourceController = class MiddlewareResourceController extends egg_1.BaseContextClass { 8 | async index() { 9 | return 'ok'; 10 | } 11 | async update() { 12 | return 'ok'; 13 | } 14 | }; 15 | MiddlewareResourceController = tslib_1.__decorate([ 16 | egg_pig_1.Resources('middleware_resource') 17 | ], MiddlewareResourceController); 18 | exports.default = MiddlewareResourceController; 19 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmVzb3VyY2VzLmpzIiwic291cmNlUm9vdC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ixtures/apps/pigapp/app/controller/middlware_rest.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let MiddlewareRestController = class MiddlewareRestController extends egg_1.BaseContextClass { 7 | async index() { 8 | return 'index'; 9 | } 10 | async update () { 11 | return 'update'; 12 | } 13 | }; 14 | 15 | MiddlewareRestController = tslib_1.__decorate([ 16 | egg_pig_1.Resources('middleware_rest') 17 | ], MiddlewareRestController); 18 | exports.default = MiddlewareRestController; 19 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWlkZGxld2FyZV9hLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsibWlkZGxld2FyZV9hLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUN2QyxxQ0FBMEM7QUFHMUMsSUFBcUIscUJBQXFCLEdBQTFDLDJCQUEyQyxTQUFRLHNCQUFnQjtJQUcvRCxLQUFLLENBQUMsR0FBRztRQUNMLE9BQU8sS0FBSyxDQUFDO0lBQ2pCLENBQUM7SUFHRCxLQUFLLENBQUMsR0FBRztRQUNMLE9BQU8sS0FBSyxDQUFDO0lBQ2pCLENBQUM7Q0FHSixDQUFBO0FBVkc7SUFEQyxhQUFHLENBQUMsS0FBSyxDQUFDOzs7O2dEQUdWO0FBR0Q7SUFEQyxhQUFHLENBQUMsS0FBSyxDQUFDOzs7O2dEQUdWO0FBVmdCLHFCQUFxQjtJQUR6QyxvQkFBVSxDQUFDLGNBQWMsQ0FBQztHQUNOLHFCQUFxQixDQWF6QztrQkFib0IscUJBQXFCIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/other.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | class TestGuard extends egg_pig_1.CanActivate { 7 | canActivate(context) { 8 | context; 9 | return Promise.resolve(true); 10 | } 11 | } 12 | let OtherController = class OtherController extends egg_1.BaseContextClass { 13 | async foo() { 14 | return ''; 15 | } 16 | async body(id) { 17 | return id; 18 | } 19 | async query(id) { 20 | return id; 21 | } 22 | async head() { 23 | return 'head'; 24 | } 25 | }; 26 | tslib_1.__decorate([ 27 | egg_pig_1.Get(), 28 | egg_pig_1.UseGuards(TestGuard), 29 | tslib_1.__metadata("design:type", Function), 30 | tslib_1.__metadata("design:paramtypes", []), 31 | tslib_1.__metadata("design:returntype", Promise) 32 | ], OtherController.prototype, "foo", null); 33 | tslib_1.__decorate([ 34 | egg_pig_1.Post('body'), 35 | tslib_1.__param(0, egg_pig_1.Body('id')), 36 | tslib_1.__metadata("design:type", Function), 37 | tslib_1.__metadata("design:paramtypes", [Object]), 38 | tslib_1.__metadata("design:returntype", Promise) 39 | ], OtherController.prototype, "body", null); 40 | tslib_1.__decorate([ 41 | egg_pig_1.Get('query'), 42 | tslib_1.__param(0, egg_pig_1.Query('id')), 43 | tslib_1.__metadata("design:type", Function), 44 | tslib_1.__metadata("design:paramtypes", [Object]), 45 | tslib_1.__metadata("design:returntype", Promise) 46 | ], OtherController.prototype, "query", null); 47 | tslib_1.__decorate([ 48 | egg_pig_1.Get('head'), 49 | egg_pig_1.Header('Cache-Control', 'no-cache'), 50 | tslib_1.__metadata("design:type", Function), 51 | tslib_1.__metadata("design:paramtypes", []), 52 | tslib_1.__metadata("design:returntype", Promise) 53 | ], OtherController.prototype, "head", null); 54 | OtherController = tslib_1.__decorate([ 55 | egg_pig_1.Controller('other/') 56 | ], OtherController); 57 | exports.default = OtherController; 58 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib3RoZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJvd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0FDQSxlQUFlLENBdUJuQztrQkF2Qm9CLGVBQWUifQ== -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/parent_controller.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const base_1 = require("../core/base"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let ParentController = class ParentController extends base_1.default { 7 | async foo() { 8 | return await this.other(); 9 | } 10 | }; 11 | tslib_1.__decorate([ 12 | egg_pig_1.Get('test'), 13 | tslib_1.__metadata("design:type", Function), 14 | tslib_1.__metadata("design:paramtypes", []), 15 | tslib_1.__metadata("design:returntype", Promise) 16 | ], ParentController.prototype, "foo", null); 17 | ParentController = tslib_1.__decorate([ 18 | egg_pig_1.Controller('parent_controller') 19 | ], ParentController); 20 | exports.default = ParentController; 21 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGFyZW50X2NvbnRyb2xsZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJwYXJlbnRfY29udHJvbGxlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSx1Q0FBNEM7QUFDNUMscUNBQTBDO0FBRzFDLElBQXFCLGdCQUFnQixHQUFyQyxzQkFBc0MsU0FBUSxjQUFjO0lBR3hELEtBQUssQ0FBQyxHQUFHO1FBQ0wsT0FBTyxNQUFNLElBQUksQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUM5QixDQUFDO0NBRUosQ0FBQTtBQUpHO0lBREMsYUFBRyxDQUFDLE1BQU0sQ0FBQzs7OzsyQ0FHWDtBQUxnQixnQkFBZ0I7SUFEcEMsb0JBQVUsQ0FBQyxtQkFBbUIsQ0FBQztHQUNYLGdCQUFnQixDQU9wQztrQkFQb0IsZ0JBQWdCIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/parent_rest_controller.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const base_1 = require("../core/base"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let ParentController = class ParentController extends base_1.default { 7 | async foo() { 8 | return await this.other(); 9 | } 10 | async index(){ 11 | let a = await this.foo(); 12 | return a +1; 13 | } 14 | }; 15 | ParentController = tslib_1.__decorate([ 16 | egg_pig_1.Restful('parent_rest_controller') 17 | ], ParentController); 18 | exports.default = ParentController; 19 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGFyZW50X2NvbnRyb2xsZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJwYXJlbnRfY29udHJvbGxlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSx1Q0FBNEM7QUFDNUMscUNBQTBDO0FBRzFDLElBQXFCLGdCQUFnQixHQUFyQyxzQkFBc0MsU0FBUSxjQUFjO0lBR3hELEtBQUssQ0FBQyxHQUFHO1FBQ0wsT0FBTyxNQUFNLElBQUksQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUM5QixDQUFDO0NBRUosQ0FBQTtBQUpHO0lBREMsYUFBRyxDQUFDLE1BQU0sQ0FBQzs7OzsyQ0FHWDtBQUxnQixnQkFBZ0I7SUFEcEMsb0JBQVUsQ0FBQyxtQkFBbUIsQ0FBQztHQUNYLGdCQUFnQixDQU9wQztrQkFQb0IsZ0JBQWdCIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/pipe.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let APipe = class APipe { 7 | async transform(val, context) { 8 | return Object.assign({}, context, { val }); 9 | } 10 | }; 11 | APipe = tslib_1.__decorate([ 12 | egg_pig_1.Injectable() 13 | ], APipe); 14 | let BPipe = class BPipe { 15 | transform(_, __) { 16 | return 1; 17 | } 18 | }; 19 | BPipe = tslib_1.__decorate([ 20 | egg_pig_1.Injectable() 21 | ], BPipe); 22 | let PipeController = class PipeController { 23 | async index(query) { 24 | this.ctx.body = query; 25 | } 26 | async param(param) { 27 | this.ctx.body = param; 28 | } 29 | async foo(body) { 30 | this.ctx.body = body; 31 | } 32 | }; 33 | tslib_1.__decorate([ 34 | egg_pig_1.Get('/query/:id'), 35 | egg_pig_1.UsePipes(APipe), 36 | tslib_1.__param(0, egg_pig_1.Query()), 37 | tslib_1.__metadata("design:type", Function), 38 | tslib_1.__metadata("design:paramtypes", [Object]), 39 | tslib_1.__metadata("design:returntype", Promise) 40 | ], PipeController.prototype, "index", null); 41 | tslib_1.__decorate([ 42 | egg_pig_1.Get('/:id'), 43 | tslib_1.__param(0, egg_pig_1.Param('id', BPipe)), 44 | tslib_1.__metadata("design:type", Function), 45 | tslib_1.__metadata("design:paramtypes", [Object]), 46 | tslib_1.__metadata("design:returntype", Promise) 47 | ], PipeController.prototype, "param", null); 48 | tslib_1.__decorate([ 49 | egg_pig_1.Post('/'), 50 | tslib_1.__param(0, egg_pig_1.Body()), 51 | tslib_1.__metadata("design:type", Function), 52 | tslib_1.__metadata("design:paramtypes", [Object]), 53 | tslib_1.__metadata("design:returntype", Promise) 54 | ], PipeController.prototype, "foo", null); 55 | PipeController = tslib_1.__decorate([ 56 | egg_pig_1.Controller('pipe') 57 | ], PipeController); 58 | exports.default = PipeController; 59 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGlwZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInBpcGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEsNkJBQXVDO0FBQ3ZDLHFDQUFrRjtBQUdsRixJQUFNLEtBQUssR0FBWDtJQUNFLEtBQUssQ0FB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FBQUcsQ0FBQyxNQUFNLENBQUM7SUFDQyxtQkFBQSxlQUFLLENBQUMsSUFBSSxFQUFFLEtBQUssQ0FBQyxDQUFBOzs7OzJDQUU5QjtBQUlEO0lBRkMsY0FBSSxDQUFDLEdBQUcsQ0FBQztJQUNULGtCQUFRLENBQUMsS0FBSyxDQUFDO0lBQ0wsbUJBQUEsY0FBSSxFQUFFLENBQUE7Ozs7eUNBRWhCO0FBakJHLGNBQWM7SUFEbkIsb0JBQVUsQ0FBQyxNQUFNLENBQUM7R0FDYixjQUFjLENBa0JuQjtBQUdELGtCQUFlLGNBQWMsQ0FBQyJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/pipetest.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | const class_validator_1 = require("class-validator"); 7 | class User { 8 | getName() { 9 | return this.firstName + ' ' + this.lastName; 10 | } 11 | } 12 | tslib_1.__decorate([ 13 | class_validator_1.IsInt(), 14 | tslib_1.__metadata("design:type", Number) 15 | ], User.prototype, "age", void 0); 16 | tslib_1.__decorate([ 17 | class_validator_1.Length(2, 10), 18 | tslib_1.__metadata("design:type", String) 19 | ], User.prototype, "firstName", void 0); 20 | tslib_1.__decorate([ 21 | class_validator_1.IsString(), 22 | tslib_1.__metadata("design:type", String) 23 | ], User.prototype, "lastName", void 0); 24 | let PipetestController = class PipetestController extends egg_1.BaseContextClass { 25 | async foo(id) { 26 | return id; 27 | } 28 | async bar(user) { 29 | return user.getName(); 30 | } 31 | async xxx(id) { 32 | return id; 33 | } 34 | }; 35 | tslib_1.__decorate([ 36 | egg_pig_1.Get('parseint'), 37 | tslib_1.__param(0, egg_pig_1.Query('id', egg_pig_1.ParseIntPipe)), 38 | tslib_1.__metadata("design:type", Function), 39 | tslib_1.__metadata("design:paramtypes", [Object]), 40 | tslib_1.__metadata("design:returntype", Promise) 41 | ], PipetestController.prototype, "foo", null); 42 | tslib_1.__decorate([ 43 | egg_pig_1.Post('validation'), 44 | tslib_1.__param(0, egg_pig_1.Body(new egg_pig_1.ValidationPipe({ transform: true }))), 45 | tslib_1.__metadata("design:type", Function), 46 | tslib_1.__metadata("design:paramtypes", [User]), 47 | tslib_1.__metadata("design:returntype", Promise) 48 | ], PipetestController.prototype, "bar", null); 49 | tslib_1.__decorate([ 50 | egg_pig_1.Get('other'), 51 | tslib_1.__param(0, egg_pig_1.Query('id', egg_pig_1.ValidationPipe)), 52 | tslib_1.__metadata("design:type", Function), 53 | tslib_1.__metadata("design:paramtypes", [Object]), 54 | tslib_1.__metadata("design:returntype", Promise) 55 | ], PipetestController.prototype, "xxx", null); 56 | PipetestController = tslib_1.__decorate([ 57 | egg_pig_1.Controller('pipetest') 58 | ], PipetestController); 59 | exports.default = PipetestController; 60 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGlwZXRlc3QuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJwaXBldGVzdC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSw2QkFBdUM7QUFDdkMscUNBQTJGO0FBQzNGLHFEQUEwRDtBQUcxRDtJQVdJLE9BQU87UUFDSCxPQUFPLElBQUksQ0FBQyxTQUFTLEdBQUcsR0FBRyxHQUFHLElBQUksQ0FBQyxRQUFRLENBQUM7SUFDaEQsQ0FBQztDQUVKO0FBWkc7SUFEQyx1QkFBSyxFQUFFOztpQ0FDSTtBQUdaO0lBREMsd0JBQU0sQ0FBQyxDQUFDLEVBQUUsRUFBRSxDQUFDOzt1Q0FDSTtBQUdsQjtJQURDLDBCQUFRLEVBQUU7O3NDQUNNO0FBVXJCLElBQXFCLGtCQUFrQixHQUF2Qyx3QkFBd0MsU0FBUSxzQkFBZ0I7SUFHNUQsS0FBSyxDQUFDLEdBQUcsQ0FBNEIsRUFBRTtRQUNuQyxPQUFPLEVBQUUsQ0FBQztJQUNkLENBQUM7SUFHRCxLQUFLLENBQUMsR0FBRyxDQUFnRCxJQUFVO1FBQy9ELE9BQU8sSUFBSSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQzFCLENBQUM7SUFHRCxLQUFLLENBQUMsR0FBRyxDQUE4QixFQUFFO1FBQ3JDLE9BQU8sRUFBRSxDQUFDO0lBQ2QsQ0FBQztDQUNKLENBQUE7QUFiRztJQURDLGFBQUcsQ0FBQyxVQUFVLENBQUM7SUFDTCxtQkFBQSxlQUFLLENBQUMsSUFBSSxFQUFFLHNCQUFZLENBQUMsQ0FBQTs7Ozs2Q0FFbkM7QUFHRDtJQURDLGNBQUksQ0FBQyxZQUFZLENBQUM7SUFDUixtQkFBQSxjQUFJLENBQUMsSUFBSSx3QkFBYyxDQUFDLEVBQUUsU0FBUyxFQUFFLElBQUksRUFBRSxDQUFDLENBQUMsQ0FBQTs7NkNBQU8sSUFBSTs7NkNBRWxFO0FBR0Q7SUFEQyxhQUFHLENBQUMsT0FBTyxDQUFDO0lBQ0YsbUJBQUEsZUFBSyxDQUFDLElBQUksRUFBRSx3QkFBYyxDQUFDLENBQUE7Ozs7NkNBRXJDO0FBZmdCLGtCQUFrQjtJQUR0QyxvQkFBVSxDQUFDLFVBQVUsQ0FBQztHQUNGLGtCQUFrQixDQWdCdEM7a0JBaEJvQixrQkFBa0IifQ== -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/render.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let APipes = class APipes extends egg_pig_1.PipeTransform { 7 | transform(val, metadata) { 8 | return 'zjl'; 9 | } 10 | }; 11 | APipes = tslib_1.__decorate([ 12 | egg_pig_1.Injectable() 13 | ], APipes); 14 | let HomeController = class HomeController extends egg_1.BaseContextClass { 15 | async index(query) { 16 | const dataList = { 17 | list: [ 18 | { id: 1, title: 'this is news 1', url: '/news/1' }, 19 | { id: 2, title: 'this is news 2', url: '/news/2' } 20 | ] 21 | }; 22 | return dataList; 23 | } 24 | async home() { 25 | return this.app.router.url('renders', {}); 26 | } 27 | }; 28 | tslib_1.__decorate([ 29 | egg_pig_1.Get(), 30 | egg_pig_1.Render('list.tpl'), 31 | tslib_1.__param(0, egg_pig_1.Query()), 32 | tslib_1.__metadata("design:type", Function), 33 | tslib_1.__metadata("design:paramtypes", [Object]), 34 | tslib_1.__metadata("design:returntype", Promise) 35 | ], HomeController.prototype, "index", null); 36 | tslib_1.__decorate([ 37 | egg_pig_1.Get('/home', { routerName: 'renders' }), 38 | tslib_1.__metadata("design:type", Function), 39 | tslib_1.__metadata("design:paramtypes", []), 40 | tslib_1.__metadata("design:returntype", Promise) 41 | ], HomeController.prototype, "home", null); 42 | HomeController = tslib_1.__decorate([ 43 | egg_pig_1.UsePipes(APipes), 44 | egg_pig_1.Controller('/render') 45 | ], HomeController); 46 | exports.default = HomeController; 47 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaG9tZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImhvbWUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEsNkJBQXVDO0FBQ3ZDLHFDQUF3RjtBQUl4RixJQUFNLE1BQU0sR0FBWixZQUFhLFNBQVEsdUJBQWE7SUFDaEMsU0FBUyxDQUFDLEdBQUcsRUFBRSxRQUFRO1FBQ3JCLE9BQU8sQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFDLENBQUM7UUFDakIsT0FBTyxDQUFDLEdBQUcsQ0FBQyxRQUFRLENBQUMsQ0FBQztRQUN0QixPQUFPLEtBQUssQ0FBQztJQUNmLENBQUM7Q0FDRixDQUFBO0FBTkssTUFBTTtJQURYLGNBQUksRUFBRTtHQUNELE1BQU0sQ0FNWDtBQU9ELElBQXFCLGNBQWMsR0FBbkMsb0JBQW9DLFNBQVEsc0JBQWdCO0lBSW5ELEtBQUssQ0FBQyxLQUFLLENBQVUsS0FBSztRQUMvQixLQUFLLElBQUksQ0FBQyxDQUFDO1FBQ1gsTUFBTSxRQUFRLEdBQUc7WUFDZixJQUFJLEVBQUU7Z0JBQ0osRUFBRSxFQUFFLEVBQUUsQ0FBQyxFQUFFLEtBQUssRUFBRSxnQkFBZ0IsRUFBRSxHQUFHLEVBQUUsU0FBUyxFQUFFO2dCQUNsRCxFQUFFLEVBQUUsRUFBRSxDQUFDLEVBQUUsS0FBSyxFQUFFLGdCQUFnQixFQUFFLEdBQUcsRUFBRSxTQUFTLEVBQUU7YUFDbkQ7U0FDRixDQUFDO1FBQ0YsT0FBTyxRQUFRLENBQUM7SUFDbEIsQ0FBQztJQUdNLEtBQUssQ0FBQyxJQUFJO1FBQ2YsT0FBTyxJQUFJLENBQUMsR0FBRyxDQUFDLE1BQU0sQ0FBQyxHQUFHLENBQUMsU0FBUyxFQUFDLEVBQUUsQ0FBQyxDQUFDO0lBQzNDLENBQUM7Q0FFRixDQUFBO0FBaEJDO0lBRkMsYUFBRyxFQUFFO0lBQ0wsZ0JBQU0sQ0FBQyxVQUFVLENBQUM7SUFDQyxtQkFBQSxlQUFLLEVBQUUsQ0FBQTs7OzsyQ0FTMUI7QUFHRDtJQURDLGFBQUcsQ0FBQyxTQUFTLEVBQUMsT0FBTyxDQUFDOzs7OzBDQUd0QjtBQWxCa0IsY0FBYztJQUZsQyxrQkFBUSxDQUFDLE1BQU0sQ0FBQztJQUNoQixvQkFBVSxDQUFDLFNBQVMsQ0FBQztHQUNELGNBQWMsQ0FvQmxDO2tCQXBCb0IsY0FBYyJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/resources.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | let CatsController = class CatsController extends egg_1.BaseContextClass { 7 | async index() { 8 | const { ctx } = this; 9 | ctx.body = this.app.router.url('cats', ''); 10 | } 11 | async new() { 12 | const { ctx } = this; 13 | ctx.body = this.app.router.url('new_cat', ''); 14 | } 15 | async show() { 16 | const { ctx } = this; 17 | ctx.body = this.app.router.url('cat', { id: 1 }); 18 | } 19 | async edit() { 20 | const { ctx } = this; 21 | ctx.body = this.app.router.url('edit_cat', { id: 1 }); 22 | } 23 | async create() { 24 | const { ctx } = this; 25 | ctx.body = this.app.router.url('cats', { id: 1 }); 26 | } 27 | async update() { 28 | const { ctx } = this; 29 | ctx.body = this.app.router.url('cat', { id: 1 }); 30 | } 31 | async destroy() { 32 | const { ctx } = this; 33 | ctx.body = this.app.router.url('cat', { id: 1 }); 34 | } 35 | async foo() { 36 | this.ctx.body = 'foo'; 37 | } 38 | }; 39 | tslib_1.__decorate([ 40 | egg_pig_1.Get('foo', {middleware:['logb']}), 41 | tslib_1.__metadata("design:type", Function), 42 | tslib_1.__metadata("design:paramtypes", []), 43 | tslib_1.__metadata("design:returntype", Promise) 44 | ], CatsController.prototype, "foo", null); 45 | CatsController = tslib_1.__decorate([ 46 | egg_pig_1.Resources('cats', { middleware: ['loga']}) 47 | ], CatsController); 48 | exports.default = CatsController; 49 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmVzb3VyY2VzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsicmVzb3VyY2VzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUN2QyxxQ0FBMEM7QUFHMUMsSUFBTSxjQUFjLEdBQXBCLG9CQUFxQixTQUFRLHNCQUFnQjtJQUV6QyxLQUFLLENBQUMsS0FBSztRQUNQLE1BQU0sRUFBRSxHQUFHLEVBQUUsR0FBRyxJQUF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FDLEVBQUMsQ0FBQyxDQUFDO0lBQ2xELENBQUM7SUFFRCxLQUFLLENBQUMsTUFBTTtRQUNSLE1BQU0sRUFBRSxHQUFHLEVBQUUsR0FBRyxJQUFJLENBQUM7UUFDckIsR0FBRyxDQUFDLElBQUksR0FBRyxJQUFJLENBQUMsR0FBRyxDQUFDLE1BQU0sQ0FBQyxHQUFHLENBQUMsS0FBSyxFQUFDLEVBQUMsRUFBRSxFQUFDLENBQUMsRUFBQyxDQUFDLENBQUM7SUFDakQsQ0FBQztJQUVELEtBQUssQ0FBQyxPQUFPO1FBQ1QsTUFBTSxFQUFFLEdBQUcsRUFBRSxHQUFHLElBQUksQ0FBQztRQUNyQixHQUFHLENBQUMsSUFBSSxHQUFHLElBQUksQ0FBQyxHQUFHLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxLQUFLLEVBQUMsRUFBQyxFQUFFLEVBQUMsQ0FBQyxFQUFDLENBQUMsQ0FBQztJQUNqRCxDQUFDO0lBR0QsS0FBSyxDQUFDLEdBQUc7UUFDTCxJQUFJLENBQUMsR0FBRyxDQUFDLElBQUksR0FBRyxLQUFLLENBQUM7SUFDMUIsQ0FBQztDQUNKLENBQUE7QUFIRztJQURDLGFBQUcsQ0FBQyxLQUFLLENBQUM7Ozs7eUNBR1Y7QUF4Q0MsY0FBYztJQURuQixtQkFBUyxDQUFDLE1BQU0sQ0FBQztHQUNaLGNBQWMsQ0F5Q25CO0FBR0Qsa0JBQWUsY0FBYyxDQUFDIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/serializer.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const class_transformer_1 = require("class-transformer"); 5 | const egg_1 = require("egg"); 6 | const egg_pig_1 = require("../../../../../../"); 7 | class RoleEntity { 8 | constructor(partial) { 9 | Object.assign(this, partial); 10 | } 11 | } 12 | class UserEntity { 13 | constructor(partial) { 14 | Object.assign(this, partial); 15 | } 16 | get fullName() { 17 | return `${this.firstName} ${this.lastName}`; 18 | } 19 | } 20 | tslib_1.__decorate([ 21 | class_transformer_1.Exclude(), 22 | tslib_1.__metadata("design:type", String) 23 | ], UserEntity.prototype, "password", void 0); 24 | tslib_1.__decorate([ 25 | class_transformer_1.Expose(), 26 | tslib_1.__metadata("design:type", Object), 27 | tslib_1.__metadata("design:paramtypes", []) 28 | ], UserEntity.prototype, "fullName", null); 29 | tslib_1.__decorate([ 30 | class_transformer_1.Transform(role => role.name), 31 | tslib_1.__metadata("design:type", RoleEntity) 32 | ], UserEntity.prototype, "role", void 0); 33 | let SerializerController = class SerializerController extends egg_1.BaseContextClass { 34 | async foo() { 35 | return [new UserEntity({ 36 | id: 1, 37 | firstName: 'jay', 38 | lastName: 'chou', 39 | password: '123456', 40 | role: new RoleEntity({ id: 1, name: 'admin' }) 41 | }), new UserEntity({ 42 | id: 2, 43 | firstName: 'kamic', 44 | lastName: 'xxxla', 45 | password: '45678', 46 | role: new RoleEntity({ id: 2, name: 'user01' }) 47 | })]; 48 | } 49 | }; 50 | tslib_1.__decorate([ 51 | egg_pig_1.Get(), 52 | tslib_1.__metadata("design:type", Function), 53 | tslib_1.__metadata("design:paramtypes", []), 54 | tslib_1.__metadata("design:returntype", Promise) 55 | ], SerializerController.prototype, "foo", null); 56 | SerializerController = tslib_1.__decorate([ 57 | egg_pig_1.Controller('serializer'), 58 | egg_pig_1.UseInterceptors(new egg_pig_1.ClassSerializerInterceptor()) 59 | ], SerializerController); 60 | exports.default = SerializerController; 61 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2VyaWFsaXplci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInNlcmlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEsNkJBQXVDO0FBQ3ZDLHlEQUErRDtBQUMvRCxxQ0FBOEY7QU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QUNqQixJQUFJLEVBQUUsSUFBSSxVQUFVLENBQUMsRUFBRSxFQUFFLEVBQUUsQ0FBQyxFQUFFLElBQUksRUFBRSxRQUFRLEVBQUUsQ0FBQzthQUNsRCxDQUFDLENBQUMsQ0FBQTtJQUNQLENBQUM7Q0FDSixDQUFBO0FBZkc7SUFEQyxhQUFHLEVBQUU7Ozs7K0NBZUw7QUFqQmdCLG9CQUFvQjtJQUZ4QyxvQkFBVSxDQUFDLFlBQVksQ0FBQztJQUN4Qix5QkFBZSxDQUFDLElBQUksb0NBQTBCLEVBQUUsQ0FBQztHQUM3QixvQkFBb0IsQ0FrQnhDO2tCQWxCb0Isb0JBQW9CIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/controller/upload.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | const pump = require('mz-modules/pump'); 7 | const fs = require("fs"); 8 | const path = require("path"); 9 | let UploadController = class UploadController extends egg_1.BaseContextClass { 10 | async index(stream) { 11 | const filename = encodeURIComponent(stream.fields.name) + path.extname(stream.filename).toLowerCase(); 12 | const target = path.join(this.config.baseDir, 'app/public', filename); 13 | const writeStream = fs.createWriteStream(target); 14 | await pump(stream, writeStream); 15 | return 'ok'; 16 | } 17 | async multiple(parts) { 18 | let stream; 19 | while ((stream = await parts()) != null) { 20 | const filename = stream.filename.toLowerCase(); 21 | const target = path.join(this.config.baseDir, 'app/public', filename); 22 | const writeStream = fs.createWriteStream(target); 23 | await pump(stream, writeStream); 24 | } 25 | return 'ok'; 26 | } 27 | async fileMethod(file) { 28 | const filename = encodeURIComponent(this.ctx.request.body.name) + path.extname(file.filename).toLowerCase(); 29 | const targetPath = path.join(this.config.baseDir, 'app/public', filename); 30 | const source = fs.createReadStream(file.filepath); 31 | const target = fs.createWriteStream(targetPath); 32 | await pump(source, target); 33 | return 'ok'; 34 | } 35 | async filesMethod(files) { 36 | for (const file of files) { 37 | const filename = file.filename.toLowerCase(); 38 | const targetPath = path.join(this.config.baseDir, 'app/public', filename); 39 | const source = fs.createReadStream(file.filepath); 40 | const target = fs.createWriteStream(targetPath); 41 | await pump(source, target); 42 | } 43 | return 'ok'; 44 | } 45 | }; 46 | tslib_1.__decorate([ 47 | egg_pig_1.Post('form'), 48 | tslib_1.__param(0, egg_pig_1.UploadedFileStream()), 49 | tslib_1.__metadata("design:type", Function), 50 | tslib_1.__metadata("design:paramtypes", [Object]), 51 | tslib_1.__metadata("design:returntype", Promise) 52 | ], UploadController.prototype, "index", null); 53 | tslib_1.__decorate([ 54 | egg_pig_1.Post('multiple'), 55 | tslib_1.__param(0, egg_pig_1.UploadedFilesStream({ autoFields: true })), 56 | tslib_1.__metadata("design:type", Function), 57 | tslib_1.__metadata("design:paramtypes", [Object]), 58 | tslib_1.__metadata("design:returntype", Promise) 59 | ], UploadController.prototype, "multiple", null); 60 | tslib_1.__decorate([ 61 | egg_pig_1.Post('file'), 62 | tslib_1.__param(0, egg_pig_1.UploadedFile()), 63 | tslib_1.__metadata("design:type", Function), 64 | tslib_1.__metadata("design:paramtypes", [Object]), 65 | tslib_1.__metadata("design:returntype", Promise) 66 | ], UploadController.prototype, "fileMethod", null); 67 | tslib_1.__decorate([ 68 | egg_pig_1.Post('files'), 69 | tslib_1.__param(0, egg_pig_1.UploadedFiles()), 70 | tslib_1.__metadata("design:type", Function), 71 | tslib_1.__metadata("design:paramtypes", [Object]), 72 | tslib_1.__metadata("design:returntype", Promise) 73 | ], UploadController.prototype, "filesMethod", null); 74 | UploadController = tslib_1.__decorate([ 75 | egg_pig_1.Controller('upload') 76 | ], UploadController); 77 | exports.default = UploadController; 78 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29udGV4dC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImNvbnRleHQudHMiXSwib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------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const tslib_1 = require("tslib"); 4 | const egg_1 = require("egg"); 5 | const egg_pig_1 = require("../../../../../../"); 6 | const User = egg_pig_1.createParamDecorator((data, ctx) => { 7 | return ctx.url + '/' + data; 8 | }); 9 | let AAPipe = class AAPipe extends egg_pig_1.PipeTransform { 10 | transform(val, metadata) { 11 | val && metadata; 12 | return val; 13 | } 14 | }; 15 | AAPipe = tslib_1.__decorate([ 16 | egg_pig_1.Injectable() 17 | ], AAPipe); 18 | let UserController = class UserController extends egg_1.BaseContextClass { 19 | async index(user) { 20 | return user; 21 | } 22 | }; 23 | tslib_1.__decorate([ 24 | egg_pig_1.Get(), 25 | tslib_1.__param(0, User('test', AAPipe)), 26 | tslib_1.__metadata("design:type", Function), 27 | tslib_1.__metadata("design:paramtypes", [Object]), 28 | tslib_1.__metadata("design:returntype", Promise) 29 | ], UserController.prototype, "index", null); 30 | UserController = tslib_1.__decorate([ 31 | egg_pig_1.Controller('/user') 32 | ], UserController); 33 | exports.default = UserController; 34 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmVuZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsicmVuZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLDZCQUF1QztBQUN2QyxxQ0FBcUY7QUFFckYsTUFBTSxJQUFJLEdBQUcsOEJBQW9CLENBQUMsQ0FBQyxJQUFJLEVBQUUsR0FBRyxFQUFFLEVBQUU7SUFDOUMsT0FBTyxHQUFHLENBQUMsSUFBSSxHQUFHLEdBQUcsR0FBRyxJQUFJLENBQUM7QUFDL0IsQ0FBQyxDQUFDLENBQUM7QUFHSCxJQUFNLEtBQUssR0FBWCxXQUFZLFNBQVEsdUJBQWE7SUFDL0IsU0FBUyxDQUFDLEdBQUcsRUFBRSxRQUFRO1FBQ3JCLEdBQUcsSUFBSSxRQUFRLENBQUM7UUFDaEIsT0FBTyxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUMsQ0FBQztRQUNqQixPQUFPLENBQUMsR0FBRyxDQUFDLFFBQVEsQ0FBQyxDQUFDO1FBQ3RCLE9BQU8sR0FBRyxDQUFDO0lBQ2IsQ0FBQztDQUNGLENBQUE7QUFQSyxLQUFLO0lBRFYsY0FBSSxFQUFFO0dBQ0QsS0FBSyxDQU9WO0FBSUQsSUFBcUIsY0FBYyxHQUFuQyxvQkFBb0MsU0FBUSxzQkFBZ0I7SUFHbkQsS0FBSyxDQUFDLEtBQUssQ0FBc0IsSUFBSTtRQUMxQyxPQUFPLElBQUksQ0FBQztJQUNkLENBQUM7Q0FHRixDQUFBO0FBTEM7SUFEQyxhQUFHLEVBQUU7SUFDYyxtQkFBQSxJQUFJLENBQUMsTUFBTSxFQUFFLEtBQUssQ0FBQyxDQUFBOzs7OzJDQUV0QztBQUxrQixjQUFjO0lBRGxDLG9CQUFVLENBQUMsT0FBTyxDQUFDO0dBQ0MsY0FBYyxDQVFsQztrQkFSb0IsY0FBYyJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/core/base.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const egg_1 = require("egg"); 4 | class BaseController extends egg_1.Controller { 5 | async other() { 6 | return await Promise.resolve(1); 7 | } 8 | } 9 | exports.default = BaseController; 10 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFzZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImJhc2UudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxNQUFNLEVBQUUsVUFBVSxFQUFFLEdBQUcsT0FBTyxDQUFDLEtBQUssQ0FBQyxDQUFDO0FBRXRDLG9CQUFvQyxTQUFRLFVBQVU7SUFDbEQsS0FBSyxDQUFDLEtBQUs7UUFDUCxPQUFPLE1BQU0sT0FBTyxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUNwQyxDQUFDO0NBQ0o7QUFKRCxpQ0FJQyJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/middleware/loga.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.default = () => { 4 | return async function (__, next) { 5 | console.log('this is loga middleare'); 6 | return next(); 7 | }; 8 | }; 9 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9nYS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImxvZ2EudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFFQSxrQkFBZSxHQUFHLEVBQUU7SUFFaEIsT0FBTyxLQUFLLFdBQVcsQ0FBQyxFQUFFLElBQUk7UUFDMUIsT0FBTyxDQUFDLEdBQUcsQ0FBQyx3QkFBd0IsQ0FBQyxDQUFDO1FBQ3RDLE9BQU8sSUFBSSxFQUFFLENBQUM7SUFDbEIsQ0FBQyxDQUFDO0FBQ04sQ0FBQyxDQUFBIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/middleware/logb.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.default = () => { 4 | return async function (_, next) { 5 | console.log('this is logb middleare'); 6 | return next(); 7 | }; 8 | }; 9 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9nYi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImxvZ2IudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFFQSxrQkFBZSxHQUFHLEVBQUU7SUFFaEIsT0FBTyxLQUFLLFdBQVcsQ0FBQyxFQUFFLElBQUk7UUFDMUIsT0FBTyxDQUFDLEdBQUcsQ0FBQyx3QkFBd0IsQ0FBQyxDQUFDO1FBQ3RDLE9BQU8sSUFBSSxFQUFFLENBQUM7SUFDbEIsQ0FBQyxDQUFDO0FBQ04sQ0FBQyxDQUFBIn0= -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/router.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const egg_pig_1 = require("../../../../../"); 4 | exports.default = (app) => { 5 | const { router, controller, middleware } = app; 6 | // egg_pig_1.MiddlewareConsumer 7 | // .setRouter(router) 8 | // .apply(middleware['loga']()) 9 | // .forRoutes('middleware_a/foo') 10 | // .apply(middleware['loga'](), middleware['logb']()) 11 | // .forRoutes(controller.middlewareB) 12 | // .apply(middleware['loga']) 13 | // .exclude({ path: '/middleware_a/foo', method: egg_pig_1.RequestMethod.GET }) 14 | // .forRoutes({path:'middleware_a/bar', method: egg_pig_1.RequestMethod.ALL},'/middleware_a/foo') 15 | // .apply(middleware['loga']) 16 | // .forRoutes(controller.middlewareResource) 17 | }; 18 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicm91dGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsicm91dGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EscUNBQTZDO0FBRzdDLGtCQUFlLENBQUMsR0FBZ0IsRUFBRSxFQUFFO0lBRWxDLE1BQU0sRUFBRSxNQUFNLEVBQUMsVUFBVSxFQUFFLFVBQVUsRUFBQyxHQUFHLEdBQUcsQ0FBQztJQUc3Qyw0QkFBa0I7U0FFZixTQUFTLENBQUMsTUFBTSxDQUFDO1NBRWpCLEtBQUssQ0FBQyxVQUFVLENBQUMsTUFBTSxDQUFDLEVBQUUsQ0FBQztTQUUzQixTQUFTLENBQ1Isa0JBQWtCLEVBQ2xCLGtCQUFrQixDQUNuQjtTQUVBLEtBQUssQ0FBQyxVQUFVLENBQUMsTUFBTSxDQUFDLEVBQUUsRUFBRSxVQUFVLENBQUMsTUFBTSxDQUFDLEVBQUUsQ0FBQztTQUVqRCxTQUFTLENBQUMsVUFBVSxDQUFDLFdBQVcsQ0FBQyxDQUFBO0FBRXRDLENBQUMsQ0FBQSJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/app/view/list.tpl: -------------------------------------------------------------------------------- 1 | Hacker News -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/config/config.default.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { 3 | value: true 4 | }); 5 | const tslib_1 = require("tslib"); 6 | const operators_1 = require("rxjs/operators"); 7 | const egg_pig_1 = require("../../../../../"); 8 | 9 | exports.default = (appInfo) => { 10 | const config = {}; 11 | // app special config 12 | config.sourceUrl = `https://github.com/eggjs/examples/tree/master/${appInfo.name}`; 13 | // override config from framework / plugin 14 | // use for cookie sign key, should change to your own and keep security 15 | config.keys = appInfo.name + '_1523969653835_3209'; 16 | // add your config here 17 | config.middleware = []; 18 | config.security = { 19 | csrf: false 20 | }; 21 | config.view = { 22 | defaultViewEngine: 'nunjucks', 23 | mapping: { 24 | '.tpl': 'nunjucks', 25 | }, 26 | }; 27 | config.multipart = { 28 | mode: 'file', 29 | }; 30 | // config.globalPrefix = 'api/v1' 31 | class Guard { 32 | canActivate(context) { 33 | if (this['ctx'].url === '/global/guard') { 34 | context; 35 | return false; 36 | } 37 | return true; 38 | } 39 | } 40 | class Pipe { 41 | transform(value, metadata) { 42 | if (/\/global\/pipe.*?/.test(this['ctx'].url)) { 43 | metadata; 44 | return 2; 45 | } 46 | return value; 47 | } 48 | } 49 | class Interceptor { 50 | intercept(context, call$) { 51 | if (this['ctx'].url === '/global/interceptor') { 52 | return call$.handle().pipe(operators_1.map(data => ({ 53 | 'global': 'global' 54 | }))); 55 | } 56 | return call$.handle().pipe(operators_1.tap(data => ({ 57 | data 58 | }))); 59 | } 60 | } 61 | class ForbiddenException extends egg_pig_1.HttpException { 62 | constructor() { 63 | super('Forbidden', egg_pig_1.HttpStatus.FORBIDDEN); 64 | } 65 | } 66 | let HttpExceptionFilter = class HttpExceptionFilter extends egg_pig_1.ExceptionFilter { 67 | catch (exception) { 68 | const ctx = this['ctx']; 69 | if (this['ctx'].url === '/global/filter') { 70 | const status = exception.getStatus(); 71 | ctx.status = status; 72 | ctx.body = { 73 | statusCode: status, 74 | message: `It's a message from the exception filter`, 75 | }; 76 | } 77 | ctx.status = exception.getStatus(); 78 | ctx.body = { 79 | statusCode: exception.getStatus(), 80 | message: exception.getResponse() 81 | }; 82 | } 83 | }; 84 | HttpExceptionFilter = tslib_1.__decorate([ 85 | egg_pig_1.Catch(ForbiddenException) 86 | ], HttpExceptionFilter); 87 | config.globalGuards = [class { 88 | canActivate(context) { 89 | return true; 90 | } 91 | }, new Guard()]; 92 | config.globalPipes = [class { 93 | transform(value, metadata) { 94 | return value; 95 | } 96 | }, new Pipe()]; 97 | config.globalInterceptors = [ 98 | class { 99 | intercept(context, call$) { 100 | return call$.handle().pipe(operators_1.tap(data => {})); 101 | } 102 | }, 103 | new Interceptor() 104 | ]; 105 | config.globalFilters = [new HttpExceptionFilter()]; 106 | return config; 107 | }; 108 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlnLmRlZmF1bHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJjb25maWcuZGVmYXVsdC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQVVBLGtCQUFlLENBQUMsT0FBcUIsRUFBRSxFQUFFO0lBQ3ZDLE1BQU0sTUFBTSxHQUFHLEVBQTRDLENBQUM7SUFFNUQscUJBQXFCO0lBQ3JCLE1BQU0sQ0FBQyxTQUFTLEdBQUcsaURBQWlELE9BQU8sQ0FBQyxJQUFJLEVBQUUsQ0FBQztJQUVuRiwwQ0FBMEM7SUFDMUMsdUVBQXVFO0lBQ3ZFLE1BQU0sQ0FBQyxJQUFJLEdBQUcsT0FBTyxDQUFDLElBQUksR0FBRyxxQkFBcUIsQ0FBQztJQUVuRCx1QkFBdUI7SUFDdkIsTUFBTSxDQUFDLFVBQVUsR0FBRyxFQUFFLENBQUM7SUFHdkIsTUFBTSxDQUFDLE1BQU0sR0FBRztRQUNkLEdBQUcsRUFBRSxJQUFJO1FBQ1QsS0FBSyxFQUFFLElBQUk7S0FDWixDQUFBO0lBR0QsTUFBTSxDQUFDLFFBQVEsR0FBRztRQUNoQixJQUFJLEVBQUUsS0FBSztLQUNaLENBQUE7SUFFRCxPQUFPLE1BQU0sQ0FBQztBQUNoQixDQUFDLENBQUMifQ== -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/config/plugin.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const plugin = { 4 | // static: true, 5 | nunjucks: { 6 | enable: true, 7 | package: 'egg-view-nunjucks', 8 | }, 9 | eggpig: { 10 | enable: true, 11 | package: 'egg-pig' 12 | } 13 | }; 14 | exports.default = plugin; 15 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGx1Z2luLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsicGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBRUEsTUFBTSxNQUFNLEdBQWM7SUFDeEIsZ0JBQWdCO0lBQ2hCLGNBQWM7SUFDZCxrQkFBa0I7SUFDbEIsa0NBQWtDO0lBQ2xDLEtBQUs7SUFFTCxNQUFNLEVBQUU7UUFDTixNQUFNLEVBQUUsSUFBSTtRQUNaLE9BQU8sRUFBRSxTQUFTO0tBQ25CO0NBQ0YsQ0FBQztBQUVGLGtCQUFlLE1BQU0sQ0FBQyJ9 -------------------------------------------------------------------------------- /test/fixtures/apps/pigapp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pigapp" 3 | } 4 | -------------------------------------------------------------------------------- /test/pig.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const mm = require('egg-mock'); 4 | const rimraf = require('mz-modules/rimraf'); 5 | const path = require('path'); 6 | 7 | describe('test/pig.test.js', () => { 8 | let app; 9 | 10 | before(() => { 11 | app = mm.app({ 12 | baseDir: 'apps/pigapp', 13 | }); 14 | return app.ready(); 15 | }); 16 | 17 | afterEach(mm.restore); 18 | after(() => rimraf(path.join(app.config.baseDir, 'app/public'))); 19 | 20 | describe('test/httpverb.js', () => { 21 | it('should GET verb/get', () => { 22 | return app.httpRequest() 23 | .get('/verb/get') 24 | .expect(200) 25 | .expect('get'); 26 | }); 27 | it('should GET verb/post', () => { 28 | return app.httpRequest() 29 | .post('/verb/post') 30 | .type('form') 31 | .send({ 32 | foo: 'bar', 33 | }) 34 | .expect(200) 35 | .expect('post'); 36 | }); 37 | it('should GET verb/head', () => { 38 | return app.httpRequest() 39 | .head('/verb/head') 40 | .expect(200) 41 | .expect(); 42 | }); 43 | it('should GET verb/patch', () => { 44 | return app.httpRequest() 45 | .patch('/verb/patch') 46 | .expect(200) 47 | .expect('patch'); 48 | }); 49 | it('should GET verb/put', () => { 50 | return app.httpRequest() 51 | .put('/verb/put') 52 | .expect(200) 53 | .expect('put'); 54 | }); 55 | it('should GET verb/delete', () => { 56 | return app.httpRequest() 57 | .delete('/verb/delete') 58 | .expect(200) 59 | .expect('delete'); 60 | }); 61 | it('should GET verb/options', () => { 62 | return app.httpRequest() 63 | .options('/verb/options') 64 | .expect(200) 65 | .expect('options'); 66 | }); 67 | }); 68 | 69 | 70 | describe('test/context', () => { 71 | it('should GET context/query', () => { 72 | return app.httpRequest() 73 | .get('/context/query?id=1') 74 | .expect(200) 75 | .expect('1'); 76 | }); 77 | it('should GET context/param', () => { 78 | return app.httpRequest() 79 | .get('/context/param/1') 80 | .expect(200) 81 | .expect('1'); 82 | }); 83 | it('should GET context/headers', () => { 84 | return app.httpRequest() 85 | .get('/context/headers') 86 | .expect(200) 87 | .expect('127'); 88 | }); 89 | it('should GET context/headers_two', () => { 90 | return app.httpRequest() 91 | .get('/context/headers_two') 92 | .expect(200) 93 | .expect('127'); 94 | }); 95 | it('should GET context/response', () => { 96 | return app.httpRequest() 97 | .get('/context/response') 98 | .expect(200) 99 | .expect('ok'); 100 | }); 101 | it('should GET context/request', () => { 102 | return app.httpRequest() 103 | .get('/context/request') 104 | .expect(200) 105 | .expect('GET'); 106 | }); 107 | it('should GET context/session', () => { 108 | return app.httpRequest() 109 | .get('/context/session') 110 | .expect(200) 111 | .expect('{}'); 112 | }); 113 | it('should GET context/body', () => { 114 | return app.httpRequest() 115 | .post('/context/body') 116 | .type('form') 117 | .send({ 118 | id: '1', 119 | }) 120 | .expect({ 121 | id: '1', 122 | }); 123 | }); 124 | }); 125 | 126 | 127 | describe('test/dep/**/*.js', () => { 128 | it('should GET dep/query', () => { 129 | return app.httpRequest() 130 | .get('/dep/query?id=1') 131 | .expect(200) 132 | .expect('1'); 133 | }); 134 | it('should GET innerdep/query', () => { 135 | return app.httpRequest() 136 | .get('/innerdep/query?id=1') 137 | .expect(200) 138 | .expect({ 139 | id: '1', 140 | }); 141 | }); 142 | 143 | }); 144 | 145 | describe('test/guard.js', () => { 146 | it('should GET guard', () => { 147 | return app.httpRequest() 148 | .get('/guard?id=1') 149 | .expect(200) 150 | .expect({ 151 | id: '1', 152 | }); 153 | }); 154 | it('should GET guard/forbiden', () => { 155 | return app.httpRequest() 156 | .get('/guard/forbiden') 157 | .expect(403); 158 | }); 159 | it('should GET guard/nothing', () => { 160 | return app.httpRequest() 161 | .get('/guard/nothing') 162 | .expect(200) 163 | .expect('nothing'); 164 | }); 165 | }); 166 | 167 | describe('test/pipe.js', () => { 168 | it('should GET pipe/query/:id', () => { 169 | return app.httpRequest() 170 | .get('/pipe/query/12?id=1') 171 | .expect(200) 172 | .expect({ 173 | type: 'QUERY', 174 | val: { 175 | id: '1', 176 | }, 177 | }); 178 | }); 179 | it('should GET pipe', () => { 180 | return app.httpRequest() 181 | .get('/pipe/11232') 182 | .expect(200) 183 | .expect('1'); 184 | }); 185 | it('should GET pipe post', () => { 186 | return app.httpRequest() 187 | .post('/pipe') 188 | .expect(200) 189 | .type('form') 190 | .send({ 191 | id: 1, 192 | }) 193 | .expect({ 194 | id: '1', 195 | }); 196 | }); 197 | }); 198 | 199 | describe('test/interceptor.js', () => { 200 | it('should GET interceptor/', () => { 201 | return app.httpRequest() 202 | .get('/interceptor') 203 | .expect(200) 204 | .expect({ 205 | query: { 206 | id: 1, 207 | }, 208 | path: '/', 209 | }); 210 | }); 211 | it('should GET interceptor/body', () => { 212 | return app.httpRequest() 213 | .get('/interceptor/body') 214 | .expect(200) 215 | .expect({ 216 | id: 1, 217 | }); 218 | }); 219 | it('should GET pipe interceptor/foo', () => { 220 | return app.httpRequest() 221 | .get('/interceptor/foo') 222 | .expect(204); 223 | }); 224 | }); 225 | 226 | 227 | describe('test/resources.js', () => { 228 | it('should GET /cats', () => { 229 | return app.httpRequest() 230 | .get('/cats') 231 | .expect(200) 232 | .expect('/cats/'); 233 | }); 234 | it('should GET /cats/new', () => { 235 | return app.httpRequest() 236 | .get('/cats/new') 237 | .expect(200) 238 | .expect('/cats/new'); 239 | }); 240 | it('should GET /cats/:id', () => { 241 | return app.httpRequest() 242 | .get('/cats/12') 243 | .expect(200) 244 | .expect('/cats/1'); 245 | }); 246 | it('should GET /cats/:id/edit', () => { 247 | return app.httpRequest() 248 | .get('/cats/12/edit') 249 | .expect(200) 250 | .expect('/cats/1/edit'); 251 | }); 252 | it('should GET /cats/create', () => { 253 | return app.httpRequest() 254 | .post('/cats') 255 | .expect(200) 256 | .expect('/cats/?id=1'); 257 | }); 258 | it('should GET /cats/update', () => { 259 | return app.httpRequest() 260 | .put('/cats/12') 261 | .expect(200) 262 | .expect('/cats/1'); 263 | }); 264 | it('should GET /cats/dectory', () => { 265 | return app.httpRequest() 266 | .delete('/cats/12') 267 | .expect(200) 268 | .expect('/cats/1'); 269 | }); 270 | it('should GET /cats/foo', () => { 271 | return app.httpRequest() 272 | .get('/cats/foo') 273 | .expect(200) 274 | .expect('foo'); 275 | }); 276 | }); 277 | 278 | describe('test/upload.js', () => { 279 | // // it('should form stream ', async () => { 280 | // // app.mockCsrf(); 281 | // // await app.httpRequest() 282 | // // .post('/upload/form') 283 | // // .field('name', 'form') 284 | // // .attach('file', path.join(__dirname, '1.jpg')) 285 | // // .expect('ok'); 286 | 287 | // // await app.httpRequest() 288 | // // .get('/public/form.jpg') 289 | // // .expect('content-length', '16424') 290 | // // .expect(200); 291 | // // }); 292 | 293 | 294 | // // it('should multiple stream', async () => { 295 | // // app.mockCsrf(); 296 | // // await app.httpRequest() 297 | // // .post('/upload/multiple') 298 | // // .field('name1', '1') 299 | // // .attach('file1', path.join(__dirname, '1.jpg')) 300 | // // .field('name2', '2') 301 | // // .attach('file2', path.join(__dirname, '2.jpg')) 302 | // // .field('name3', '3') 303 | // // .expect('ok'); 304 | 305 | // // await app.httpRequest() 306 | // // .get('/public/1.jpg') 307 | // // .expect('content-length', '16424') 308 | // // .expect(200); 309 | 310 | // // await app.httpRequest() 311 | // // .get('/public/2.jpg') 312 | // // .expect('content-length', '16424') 313 | // // .expect(200); 314 | // // }); 315 | 316 | // // it('should form file ', async () => { 317 | // // app.mockCsrf(); 318 | // // await app.httpRequest() 319 | // // .post('/upload/file') 320 | // // .field('name', '3') 321 | // // .attach('file', path.join(__dirname, '1.jpg')) 322 | // // .expect('ok'); 323 | 324 | // // await app.httpRequest() 325 | // // .get('/public/3.jpg') 326 | // // .expect('content-length', '16424') 327 | // // .expect(200); 328 | // // }); 329 | 330 | 331 | it('should multiple files ', async () => { 332 | app.mockCsrf(); 333 | await app.httpRequest() 334 | .post('/upload/files') 335 | .field('name1', '1') 336 | .attach('file1', path.join(__dirname, '1.jpg')) 337 | .field('name2', '2') 338 | .attach('file2', path.join(__dirname, '2.jpg')) 339 | .field('name3', '3') 340 | .expect('ok'); 341 | 342 | await app.httpRequest() 343 | .get('/public/1.jpg') 344 | .expect('content-length', '16424') 345 | .expect(200); 346 | 347 | await app.httpRequest() 348 | .get('/public/2.jpg') 349 | .expect('content-length', '16424') 350 | .expect(200); 351 | }); 352 | }); 353 | 354 | 355 | describe('test/render.js', () => { 356 | it('should GET render/', () => { 357 | return app.httpRequest() 358 | .get('/render?id=1') 359 | .expect(200) 360 | .expect('Hacker News'); 361 | }); 362 | it('should GET render/home', () => { 363 | return app.httpRequest() 364 | .get('/render/home') 365 | .expect(200) 366 | .expect('/render/home'); 367 | }); 368 | }); 369 | 370 | describe('test/user.js', () => { 371 | it('should GET user', () => { 372 | return app.httpRequest() 373 | .get('/user') 374 | .expect(200) 375 | .expect('/user/test'); 376 | }); 377 | }); 378 | 379 | describe('test/controller_options.js', () => { 380 | it('should GET controller_options/foo', () => { 381 | return app.httpRequest() 382 | .get('/controller_options/foo') 383 | .expect(200) 384 | .expect('foo'); 385 | }); 386 | it('should GET controller_options/bar', () => { 387 | return app.httpRequest() 388 | .get('/controller_options/bar') 389 | .expect(200) 390 | .expect('bar'); 391 | }); 392 | }); 393 | 394 | 395 | describe('test/middleware.js', () => { 396 | it('should GET middleware_a/foo', () => { 397 | return app.httpRequest() 398 | .get('/middleware_a/foo') 399 | .expect(200) 400 | .expect('foo'); 401 | }); 402 | it('should GET middleware_a/bar', () => { 403 | return app.httpRequest() 404 | .get('/middleware_a/bar') 405 | .expect(200) 406 | .expect('bar'); 407 | }); 408 | it('should GET middleware_b/foo', () => { 409 | return app.httpRequest() 410 | .get('/middleware_b/foo') 411 | .expect(200) 412 | .expect('foo'); 413 | }); 414 | it('should GET middleware_b/bar', () => { 415 | return app.httpRequest() 416 | .get('/middleware_b/bar') 417 | .expect(200) 418 | .expect('bar'); 419 | }); 420 | }); 421 | 422 | describe('test/middleware_resource.js', () => { 423 | it('should GET /middleware_resource', () => { 424 | return app.httpRequest() 425 | .get('/middleware_resource') 426 | .expect(200) 427 | .expect('ok'); 428 | }); 429 | it('should GET /middleware_resource', () => { 430 | return app.httpRequest() 431 | .put('/middleware_resource/12') 432 | .expect(200) 433 | .expect('ok'); 434 | }); 435 | }); 436 | 437 | 438 | describe('test/filter.js', () => { 439 | it('should GET filter/common', () => { 440 | return app.httpRequest() 441 | .get('/filter/common') 442 | .expect(500) 443 | .expect('{"error":"error"}'); 444 | }); 445 | it('should GET filter/httpexception', () => { 446 | return app.httpRequest() 447 | .get('/filter/httpexception') 448 | .expect(403) 449 | .expect('{"statusCode":403,"message":"Forbidden"}'); 450 | }); 451 | it('should GET filter/another', () => { 452 | return app.httpRequest() 453 | .get('/filter/another') 454 | .expect(403) 455 | .expect('{"statusCode":403,"path":"/filter/another"}'); 456 | }); 457 | it('should GET filter/forbiden', () => { 458 | return app.httpRequest() 459 | .get('/filter/forbiden') 460 | .expect(403) 461 | .expect('{"statusCode":403,"message":"Forbidden"}'); 462 | }); 463 | }); 464 | 465 | 466 | describe('test/helper.js', () => { 467 | it('should GET helper/forbiden', () => { 468 | return app.httpRequest() 469 | .get('/helper') 470 | .expect(200) 471 | .expect('admin'); 472 | }); 473 | }); 474 | 475 | describe('test/exception.js', () => { 476 | it('should GET exception/forbiden', () => { 477 | return app.httpRequest() 478 | .get('/exception/forbiden') 479 | .expect(403) 480 | .expect('{"statusCode":403,"error":"Forbidden"}'); 481 | }); 482 | it('should GET exception/badrequest', () => { 483 | return app.httpRequest() 484 | .get('/exception/badrequest') 485 | .expect(400) 486 | .expect('{"statusCode":400,"error":"Bad Request"}'); 487 | }); 488 | it('should GET exception/unauthorized', () => { 489 | return app.httpRequest() 490 | .get('/exception/unauthorized') 491 | .expect(401) 492 | .expect('{"statusCode":401,"error":"Unauthorized"}'); 493 | }); 494 | it('should GET exception/notfound', () => { 495 | return app.httpRequest() 496 | .get('/exception/notfound') 497 | .expect(404) 498 | .expect('{"statusCode":404,"error":"Not Found"}'); 499 | }); 500 | it('should GET exception/notacceptable', () => { 501 | return app.httpRequest() 502 | .get('/exception/notacceptable') 503 | .expect(406) 504 | .expect('{"statusCode":406,"error":"Not Acceptable"}'); 505 | }); 506 | it('should GET exception/timeout', () => { 507 | return app.httpRequest() 508 | .get('/exception/timeout') 509 | .expect(408) 510 | .expect('{"statusCode":408,"error":"Request Timeout"}'); 511 | }); 512 | it('should GET exception/conflict', () => { 513 | return app.httpRequest() 514 | .get('/exception/conflict') 515 | .expect(409) 516 | .expect('{"statusCode":409,"error":"Conflict"}'); 517 | }); 518 | it('should GET exception/gone', () => { 519 | return app.httpRequest() 520 | .get('/exception/gone') 521 | .expect(410) 522 | .expect('{"statusCode":410,"error":"Gone"}'); 523 | }); 524 | it('should GET exception/payload', () => { 525 | return app.httpRequest() 526 | .get('/exception/payload') 527 | .expect(413) 528 | .expect('{"statusCode":413,"error":"Payload Too Large"}'); 529 | }); 530 | it('should GET exception/unsupport', () => { 531 | return app.httpRequest() 532 | .get('/exception/unsupport') 533 | .expect(415) 534 | .expect('{"statusCode":415,"error":"Unsupported Media Type"}'); 535 | }); 536 | it('should GET exception/unprocess', () => { 537 | return app.httpRequest() 538 | .get('/exception/unprocess') 539 | .expect(422) 540 | .expect('{"statusCode":422,"error":"Unprocessable Entity"}'); 541 | }); 542 | it('should GET exception/internal', () => { 543 | return app.httpRequest() 544 | .get('/exception/internal') 545 | .expect(500) 546 | .expect('{"statusCode":500,"error":"Internal Server Error"}'); 547 | }); 548 | it('should GET exception/notimplement', () => { 549 | return app.httpRequest() 550 | .get('/exception/notimplement') 551 | .expect(501) 552 | .expect('{"statusCode":501,"error":"Not Implemented"}'); 553 | }); 554 | it('should GET exception/service', () => { 555 | return app.httpRequest() 556 | .get('/exception/service') 557 | .expect(503) 558 | .expect('{"statusCode":503,"error":"Service Unavailable"}'); 559 | }); 560 | it('should GET exception/badgateway', () => { 561 | return app.httpRequest() 562 | .get('/exception/badgateway') 563 | .expect(502) 564 | .expect('{"statusCode":502,"error":"Bad Gateway"}'); 565 | }); 566 | it('should GET exception/gatewaytimeout', () => { 567 | return app.httpRequest() 568 | .get('/exception/gatewaytimeout') 569 | .expect(504) 570 | .expect('{"statusCode":504,"error":"Gateway Timeout"}'); 571 | }); 572 | }); 573 | 574 | describe('test/other.js', () => { 575 | it('should GET other', () => { 576 | return app.httpRequest() 577 | .get('/other') 578 | .expect(200) 579 | .expect(''); 580 | }); 581 | it('should GET other/post', () => { 582 | return app.httpRequest() 583 | .post('/other/body') 584 | .type('form') 585 | .send({ 586 | id: '1', 587 | }) 588 | .expect('1'); 589 | }); 590 | it('should GET other/query', () => { 591 | return app.httpRequest() 592 | .get('/other/query?id=1') 593 | .expect(200) 594 | .expect('1'); 595 | }); 596 | it('should GET other/head', () => { 597 | return app.httpRequest() 598 | .get('/other/head') 599 | .expect(200) 600 | .expect('head'); 601 | }); 602 | }); 603 | 604 | describe('test/header.js', () => { 605 | it('should GET header', () => { 606 | return app.httpRequest() 607 | .get('/header/etag') 608 | .expect('ETag', '123') 609 | .expect(200) 610 | .expect('ok'); 611 | }); 612 | it('should GET header/other', () => { 613 | return app.httpRequest() 614 | .get('/header/other') 615 | .expect('Etag', '1234') 616 | .expect('Last-Modified', '2018-9-1') 617 | .expect('ok'); 618 | }); 619 | }); 620 | 621 | describe('test/global.js', () => { 622 | it('should GET guard', () => { 623 | return app.httpRequest() 624 | .get('/global/guard') 625 | .expect(403) 626 | .expect('{"statusCode":403,"error":"Forbidden","message":"Forbidden resource"}'); 627 | }); 628 | it('should GET pipe', () => { 629 | return app.httpRequest() 630 | .get('/global/pipe') 631 | .expect(200) 632 | .expect('2'); 633 | }); 634 | it('should GET interceptor', () => { 635 | return app.httpRequest() 636 | .get('/global/interceptor') 637 | .expect(200) 638 | .expect('{"global":"global"}'); 639 | }); 640 | it('should GET guard', () => { 641 | return app.httpRequest() 642 | .get('/global/filter') 643 | .expect(400) 644 | .expect('{"statusCode":400,"message":"exception"}'); 645 | }); 646 | }); 647 | 648 | describe('test/httpcode.js', () => { 649 | it('should GET httpcode/get', () => { 650 | return app.httpRequest() 651 | .get('/httpcode/get') 652 | .expect(404) 653 | .expect('ok'); 654 | }); 655 | it('should GET httpcode/post', () => { 656 | return app.httpRequest() 657 | .post('/httpcode/post') 658 | .type('form') 659 | .send({ foo: 'bar' }) 660 | .expect(400) 661 | .expect('ok'); 662 | }); 663 | }); 664 | 665 | describe('test/pipetest.js', () => { 666 | it('should GET pipetest/parseint', () => { 667 | return app.httpRequest() 668 | .get('/pipetest/parseint?id=12') 669 | .expect(200) 670 | .expect('12'); 671 | }); 672 | it('should GET bad pipetest/parseint', () => { 673 | return app.httpRequest() 674 | .get('/pipetest/parseint?id=zjl') 675 | .expect(400) 676 | .expect('{"statusCode":400,"error":"Bad Request","message":"Validation failed (numeric string is expected)"}'); 677 | }); 678 | it('should POST pipetest/validation', () => { 679 | return app.httpRequest() 680 | .post('/pipetest/validation') 681 | .type('json') 682 | .send({ 683 | age: 12, 684 | firstName: 'jay', 685 | lastName: 'chou', 686 | }) 687 | .expect(201) 688 | .expect('jay chou'); 689 | }); 690 | it('should POST bad pipetest/validation', () => { 691 | return app.httpRequest() 692 | .post('/pipetest/validation') 693 | .type('json') 694 | .send({ 695 | age: 12, 696 | firstName: 'y', 697 | lastName: 'chou', 698 | }) 699 | .expect(400) 700 | .expect('{"statusCode":400,"error":"Bad Request","message":[{"target":{"age":12,"firstName":"y","lastName":"chou"},"value":"y","property":"firstName","children":[],"constraints":{"length":"firstName must be longer than or equal to 2 characters"}}]}'); 701 | }); 702 | it('should get pipetest/other', () => { 703 | return app.httpRequest() 704 | .get('/pipetest/other?id=12') 705 | .expect(200) 706 | .expect('12'); 707 | }); 708 | }); 709 | 710 | describe('test/middleware_rest.js', () => { 711 | it('should GET /middleware_rest', () => { 712 | return app.httpRequest() 713 | .get('/middleware_rest') 714 | .expect(200) 715 | .expect('index'); 716 | }); 717 | it('should put /middleware_rest', () => { 718 | return app.httpRequest() 719 | .put('/middleware_rest/12') 720 | .expect(200) 721 | .expect('update'); 722 | }); 723 | }); 724 | 725 | 726 | describe('test/parent_controller.js', () => { 727 | it('should GET /parent_controller/test', () => { 728 | return app.httpRequest() 729 | .get('/parent_controller/test') 730 | .expect(200) 731 | .expect('1'); 732 | }); 733 | }); 734 | 735 | 736 | describe('test/parent_rest_controller.js', () => { 737 | it('should GET /parent_rest_controller', () => { 738 | return app.httpRequest() 739 | .get('/parent_rest_controller') 740 | .expect(200) 741 | .expect('2'); 742 | }); 743 | }); 744 | 745 | 746 | describe('test/serializer.js', () => { 747 | it('should GET /serializer', () => { 748 | return app.httpRequest() 749 | .get('/serializer') 750 | .expect(200) 751 | .expect('[{"id":1,"firstName":"jay","lastName":"chou","role":"admin","fullName":"jay chou"},{"id":2,"firstName":"kamic","lastName":"xxxla","role":"user01","fullName":"kamic xxxla"}]'); 752 | }); 753 | }); 754 | 755 | describe('test/exportcommon.js', () => { 756 | it('should GET /exports/test', () => { 757 | return app.httpRequest() 758 | .get('/exports/test') 759 | .expect(200) 760 | .expect('hello'); 761 | }); 762 | }); 763 | 764 | }); 765 | 766 | --------------------------------------------------------------------------------