Skip to content

Commit db902ed

Browse files
authored
Merge pull request #189 from netes/fix-interceptor-readme
Fix instructions about creating interceptors
2 parents e18178a + 128ab42 commit db902ed

File tree

1 file changed

+34
-35
lines changed

1 file changed

+34
-35
lines changed

README.md

Lines changed: 34 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ You can use routing-controllers with [express.js][1] or [koa.js][2].
101101
Optionally you can also install their typings:
102102

103103
`npm install @types/koa @types/koa-router @types/koa-bodyparser --save`
104-
104+
105105
4. Its important to set these options in `tsconfig.json` file of your project:
106106

107107
```json
@@ -110,7 +110,7 @@ You can use routing-controllers with [express.js][1] or [koa.js][2].
110110
"experimentalDecorators": true
111111
}
112112
```
113-
113+
114114
## Example of usage
115115

116116
1. Create a file `UserController.ts`
@@ -157,12 +157,12 @@ You can use routing-controllers with [express.js][1] or [koa.js][2].
157157
import "reflect-metadata"; // this shim is required
158158
import {createExpressServer} from "routing-controllers";
159159
import {UserController} from "./UserController";
160-
160+
161161
// creates express app, registers all controller routes and returns you express app instance
162162
const app = createExpressServer({
163163
controllers: [UserController] // we specify controllers we want to use
164164
});
165-
165+
166166
// run express application on port 3000
167167
app.listen(3000);
168168
```
@@ -176,10 +176,10 @@ If you open `http://localhost:3000/users/1` you will see `This action returns us
176176

177177
#### Working with json
178178

179-
If you are designing a REST API where your endpoints always receive and return JSON then
180-
you can use `@JsonController` decorator instead of `@Controller`.
179+
If you are designing a REST API where your endpoints always receive and return JSON then
180+
you can use `@JsonController` decorator instead of `@Controller`.
181181
This will guarantee you that data returned by your controller actions always be transformed to JSON
182-
and `Content-Type` header will be always set to `application/json`.
182+
and `Content-Type` header will be always set to `application/json`.
183183
It will also guarantee `application/json` header is understood from the requests and the body parsed as JSON:
184184

185185
```typescript
@@ -281,7 +281,7 @@ export class UserController {
281281

282282
> note: koa users can also use `@Ctx() context` to inject koa's Context object.
283283

284-
#### Pre-configure express/koa
284+
#### Pre-configure express/koa
285285

286286
If you have, or if you want to create and configure express app separately,
287287
you can use `useExpressServer` instead of `createExpressServer` function:
@@ -650,12 +650,12 @@ getOne() {
650650
```
651651

652652
To use rendering ability make sure to configure express / koa properly.
653-
To use rendering ability with Koa you will need to use a rendering 3rd party such as [koa-views](https://github.com/queckezz/koa-views/),
653+
To use rendering ability with Koa you will need to use a rendering 3rd party such as [koa-views](https://github.com/queckezz/koa-views/),
654654
koa-views is the only render middleware that has been tested.
655655

656656
#### Throw HTTP errors
657657

658-
If you want to return errors with specific error codes, there is an easy way:
658+
If you want to return errors with specific error codes, there is an easy way:
659659

660660
```typescript
661661
@Get("/users/:id")
@@ -664,7 +664,7 @@ getOne(@Param("id") id: number) {
664664
const user = this.userRepository.findOneById(id);
665665
if (!user)
666666
throw new NotFoundError(`User was not found.`); // message is optional
667-
667+
668668
return user;
669669
}
670670
```
@@ -693,7 +693,7 @@ You can also create and use your own errors by extending `HttpError` class.
693693

694694
#### Enable CORS
695695

696-
Since CORS is a future that is used almost in any web-api application,
696+
Since CORS is a future that is used almost in any web-api application,
697697
you can enable it in routing-controllers options.
698698

699699
```typescript
@@ -798,14 +798,14 @@ Here is example of creating middleware for express.js:
798798
1. There are two ways of creating middleware:
799799

800800
First, you can create a simple middleware function:
801-
801+
802802
```typescript
803803
export function loggingMiddleware(request: any, response: any, next?: (err?: any) => any): any {
804804
console.log("do something...");
805805
next();
806806
}
807807
```
808-
808+
809809
Second you can create a class:
810810

811811
```typescript
@@ -857,7 +857,7 @@ Here is example of creating middleware for koa.js:
857857
1. There are two ways of creating middleware:
858858

859859
First, you can create a simple middleware function:
860-
860+
861861
```typescript
862862
export function use(context: any, next: (err?: any) => Promise<any>): Promise<any> {
863863
console.log("do something before execution...");
@@ -868,7 +868,7 @@ Here is example of creating middleware for koa.js:
868868
});
869869
}
870870
```
871-
871+
872872
Second you can create a class:
873873

874874
```typescript
@@ -970,7 +970,7 @@ Error handlers work same way as middlewares, but implement `ExpressErrorMiddlewa
970970
971971
}
972972
```
973-
973+
974974
Custom error handlers are invoked after the default error handler, so you won't be able to change response code or headers.
975975
To prevent this, you have to disable default error handler by specifying `defaultErrorHandler` option in createExpressServer or useExpressServer:
976976

@@ -1002,7 +1002,7 @@ It works pretty much the same as middlewares.
10021002

10031003
### Interceptor function
10041004

1005-
The easiest way is to use functions directly passed to `@UseInterceptor` of the action.
1005+
The easiest way is to use functions directly passed to `@UseInterceptor` of the action.
10061006

10071007
```typescript
10081008
import {Get, Param, UseInterceptor} from "routing-controllers";
@@ -1011,7 +1011,7 @@ import {Get, Param, UseInterceptor} from "routing-controllers";
10111011

10121012
@Get("/users")
10131013
@UseInterceptor(function(action: Action, content: any) {
1014-
// here you have content returned by this action. you can replace something
1014+
// here you have content returned by this action. you can replace something
10151015
// in it and return a replaced result. replaced result will be returned to the user
10161016
return content.replace(/Mike/gi, "Michael");
10171017
})
@@ -1020,7 +1020,7 @@ getOne(@Param("id") id: number) {
10201020
}
10211021
```
10221022

1023-
You can use `@UseInterceptor` per-action, on per-controller.
1023+
You can use `@UseInterceptor` per-action, on per-controller.
10241024
If its used per-controller then interceptor will apply to all controller actions.
10251025

10261026
### Interceptor classes
@@ -1030,13 +1030,12 @@ You can also create a class and use it with `@UseInterceptor` decorator:
10301030
```typescript
10311031
import {Interceptor, InterceptorInterface, Action} from "routing-controllers";
10321032

1033-
@Interceptor()
10341033
export class NameCorrectionInterceptor implements InterceptorInterface {
1035-
1034+
10361035
intercept(action: Action, content: any) {
10371036
return content.replace(/Mike/gi, "Michael");
10381037
}
1039-
1038+
10401039
}
10411040
```
10421041

@@ -1065,11 +1064,11 @@ import {Interceptor, InterceptorInterface, Action} from "routing-controllers";
10651064

10661065
@Interceptor()
10671066
export class NameCorrectionInterceptor implements InterceptorInterface {
1068-
1067+
10691068
intercept(action: Action, content: any) {
10701069
return content.replace(/Mike/gi, "Michael");
10711070
}
1072-
1071+
10731072
}
10741073
```
10751074

@@ -1111,7 +1110,7 @@ export class UserController {
11111110
}
11121111
```
11131112

1114-
If `User` is an interface - then simple literal object will be created.
1113+
If `User` is an interface - then simple literal object will be created.
11151114
If its a class - then instance of this class will be created.
11161115

11171116
This technique works not only with `@Body`, but also with `@Param`, `@QueryParam`, `@BodyParam` and other decorators.
@@ -1121,7 +1120,7 @@ If you want to disable it simply pass `classTransformer: false` to createExpress
11211120

11221121
## Auto validating action params
11231122

1124-
Sometimes parsing a json object into instance of some class is not enough.
1123+
Sometimes parsing a json object into instance of some class is not enough.
11251124
E.g. `class-transformer` doesn't check whether the property's types are correct, so you can get runtime error if you rely on TypeScript type safe. Also you may want to validate the object to check e.g. whether the password string is long enough or entered e-mail is correct.
11261125

11271126
It can be done easily thanks to integration with [class-validator][9]. This behaviour is **enabled** by default. If you want to disable it, you need to do it explicitly e.g. by passing `validation: false` option on application bootstrap:
@@ -1141,7 +1140,7 @@ If you want to turn on the validation only for some params, not globally for eve
11411140
login(@Body({ validate: true }) user: User) {
11421141
```
11431142
1144-
Now you need to define the class which type will be used as type of controller's method param.
1143+
Now you need to define the class which type will be used as type of controller's method param.
11451144
Decorate the properties with appropriate validation decorators.
11461145
```typescript
11471146
export class User {
@@ -1170,7 +1169,7 @@ export class UserController {
11701169

11711170
}
11721171
```
1173-
If the param doesn't satisfy the requirements defined by class-validator decorators,
1172+
If the param doesn't satisfy the requirements defined by class-validator decorators,
11741173
an error will be thrown and captured by routing-controller, so the client will receive 400 Bad Request and JSON with nice detailed [Validation errors](https://github.com/pleerock/class-validator#validation-errors) array.
11751174
11761175
If you need special options for validation (groups, skipping missing properties, etc.) or transforming (groups, excluding prefixes, versions, etc.), you can pass them as global config as `validation ` in createExpressServer method or as a local `validate` setting for method parameter - `@Body({ validate: localOptions })`.
@@ -1198,13 +1197,13 @@ createExpressServer({
11981197
// either promise that resolves a boolean value
11991198
// demo code:
12001199
const token = action.request.headers["authorization"];
1201-
1200+
12021201
const user = await getEntityManager().findOneByToken(User, token);
12031202
if (user && !roles.length)
12041203
return true;
12051204
if (user && roles.find(role => user.roles.indexOf(role) !== -1))
12061205
return true;
1207-
1206+
12081207
return false;
12091208
}
12101209
}).listen(3000);
@@ -1307,7 +1306,7 @@ export class UsersController {
13071306
13081307
## Custom parameter decorators
13091308
1310-
You can create your own parameter decorators.
1309+
You can create your own parameter decorators.
13111310
Here is simple example how "session user" can be implemented using custom decorators:
13121311
13131312
```typescript
@@ -1335,9 +1334,9 @@ export class QuestionController {
13351334
// here you'll have user authorized and you can safely save your question
13361335
// in the case if user returned your undefined from the database and "required"
13371336
// parameter was set, routing-controllers will throw you ParameterRequired error
1338-
}
1339-
1340-
1337+
}
1338+
1339+
13411340
}
13421341
```
13431342

0 commit comments

Comments
 (0)