Skip to content

Controller inheritance #577

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
dc50de6
Add a useResponseClassTransformer global option
Nov 22, 2017
2346d51
Update comment, remove redundant null check
Nov 24, 2017
0fbe188
Merge remote-tracking branch 'upstream/master'
Dec 3, 2017
be17c80
Implement route/controller-specific transform options
Dec 4, 2017
778ea0b
Implement TransformationOptions instead of extending it in controller…
Dec 5, 2017
c408966
Fix inconsistencies in transform options tests
Dec 5, 2017
0d9ebae
Merge
Dec 26, 2017
19a931a
Test action only transforming requests, cleanup default values from t…
Dec 26, 2017
b93ab85
Correct method signature of CustomMiddlewareThatThrows.use()
yazshel Sep 10, 2018
e8d6976
Fix typo Wich => Which in test action and route names
yazshel Sep 10, 2018
56233d9
Add test of error handling in Koa async middlewares
yazshel Sep 10, 2018
c36d1b2
Fix incorrect handling of rejected promises returned from middleware …
yazshel Sep 10, 2018
6783000
Export SessionParam at index
yinxulai Dec 17, 2019
44abb53
Add support for wildcard "all" routes
ArthurMelin Feb 10, 2020
8e36754
Document @All in README
ArthurMelin Feb 20, 2020
6fc927d
chore: add another example for using the response directly
phikes Mar 11, 2020
f023c7e
style: don't you
phikes Mar 11, 2020
ee0e05d
Readme: replaced url pleerock/class-validator -> typestack/class-vali…
adaamz May 18, 2020
a1b2606
https://github.com/typestack/routing-controllers/pull/301
ivanproskuryakov May 24, 2020
9a4befe
Merge branch 'ideal123' into next
jotamorais May 28, 2020
ab34d5c
Merge branch 'koa-middleware-error-handling-fix' of https://github.co…
jotamorais May 28, 2020
09a6d6a
Merge branch 'koa-middleware-error-handling-fix'
jotamorais May 28, 2020
311f2fb
Merge branch 'master' of https://github.com/Elassyo/routing-controlle…
jotamorais May 28, 2020
8395465
Merge branch 'Elassyo-master' into next
jotamorais May 28, 2020
53340bc
Merge branch 'add-example-for-req-res-usage' of https://github.com/ph…
jotamorais May 28, 2020
93cf01d
Merge branch 'phikes-add-example-for-req-res-usage' into next
jotamorais May 28, 2020
cd26ae1
Merge branch 'master' of https://github.com/epiphone/routing-controll…
jotamorais May 28, 2020
9b42abd
Merge branch 'epiphone-master' into next
jotamorais May 28, 2020
b4bf77c
Fix issue after merging PR#329
jotamorais May 28, 2020
44f809e
implementation
ivanpadavan Oct 2, 2017
ddee6cd
example
ivanpadavan Oct 2, 2017
b34f47e
Merge branch 'ivanpadavan-controller-inheritance' into next
jotamorais May 28, 2020
7999100
Merge pull request #564 from adaamz/patch-1
jotamorais May 29, 2020
98e46b9
Merge pull request #526 from yinxulai/patch-1
jotamorais May 29, 2020
1540b2f
Add support for wildcard "all" routes
ArthurMelin Feb 10, 2020
7471682
Document @All in README
ArthurMelin Feb 20, 2020
17fbbe9
Add middleware guard to prevent multiple routes execution per request
ArthurMelin May 29, 2020
694901a
Add tests for All decorator
ArthurMelin May 29, 2020
9e8b03a
Merge branch 'fix-double-exec' of https://github.com/Elassyo/routing-…
jotamorais May 29, 2020
678cb86
Merge branch 'Elassyo-fix-double-exec' into next
jotamorais May 29, 2020
7fc4728
Merge branch 'master' of https://github.com/Elassyo/routing-controlle…
jotamorais May 29, 2020
9256d08
Merge branch 'Elassyo-master' into next
jotamorais May 29, 2020
cb953ca
Bump version for release candidate 0.9.0-alpha.2
jotamorais May 29, 2020
b3bde95
Update all dependencies to latest
jotamorais Jun 5, 2020
11dbf79
Merge branch 'next' into crontroller-inheritance
ivanproskuryakov Jun 7, 2020
e3c9da5
Fix typo in example
stefan-malcek Jun 7, 2020
70a3465
Merge pull request #572 from stefan-malcek/patch-1
jotamorais Jun 8, 2020
73b59e0
Updates for controller inheritance sample to highlight the benefits o…
ivanproskuryakov Jun 8, 2020
d0793f2
class and method descriptions added
ivanproskuryakov Jun 14, 2020
dd4e9f0
Unit tests to secure changes of MetadataBuilder::createActions method…
ivanproskuryakov Jun 14, 2020
60a5c24
update readme with the details about new controller inheritance feature
ivanproskuryakov Jun 15, 2020
3618cf8
fixing tests, flushing & building MetadataArgsStorage in the begging …
ivanproskuryakov Jun 17, 2020
9be5fc6
Merge branch 'next' into controller-inheritance
ivanproskuryakov Jun 17, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 63 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ You can use routing-controllers with [express.js][1] or [koa.js][2].
- [Throw HTTP errors](#throw-http-errors)
- [Enable CORS](#enable-cors)
- [Default settings](#default-settings)
- [Selectively disabling request/response transform](#selectively-disable-requestresponse-transforming)
* [Using middlewares](#using-middlewares)
+ [Use exist middleware](#use-exist-middleware)
+ [Creating your own express middleware](#creating-your-own-express-middleware)
Expand All @@ -54,6 +55,7 @@ You can use routing-controllers with [express.js][1] or [koa.js][2].
+ [Interceptor classes](#interceptor-classes)
+ [Global interceptors](#global-interceptors)
* [Creating instances of classes from action params](#creating-instances-of-classes-from-action-params)
* [Controller inheritance](#controller-inheritance)
* [Auto validating action params](#auto-validating-action-params)
* [Using authorization features](#using-authorization-features)
- [@Authorized decorator](#authorized-decorator)
Expand Down Expand Up @@ -262,10 +264,19 @@ import {Controller, Req, Res, Get} from "routing-controllers";
export class UserController {

@Get("/users")
getAll(@Req() request: any, @Res() response: any) {
getAllUsers(@Req() request: any, @Res() response: any) {
return response.send("Hello response!");
}

@Get("/posts")
getAllPosts(@Req() request: any, @Res() response: any) {
// some response functions don't return the response object,
// so it needs to be returned explicitly
response.redirect("/users");

return response;
}

}
```

Expand Down Expand Up @@ -554,7 +565,7 @@ You can specify a custom ContentType header:

```typescript
@Get("/users")
@ContentType("text/cvs")
@ContentType("text/csv")
getUsers() {
// ...
}
Expand Down Expand Up @@ -733,7 +744,7 @@ There are set of prepared errors you can use:
* UnauthorizedError


You can also create and use your own errors by extending `HttpError` class.
You can also create and use your own errors by extending `HttpError` class.
To define the data returned to the client, you could define a toJSON method in your error.

```typescript
Expand All @@ -755,7 +766,7 @@ class DbError extends HttpError {
}
}
}
```
```

#### Enable CORS

Expand Down Expand Up @@ -796,7 +807,7 @@ app.listen(3000);

#### Default settings

You can override default status code in routing-controllers options.
You can override default status code in routing-controllers options.

```typescript
import "reflect-metadata";
Expand All @@ -809,9 +820,9 @@ const app = createExpressServer({
//with this option, null will return 404 by default
nullResultCode: 404,

//with this option, void or Promise<void> will return 204 by default
//with this option, void or Promise<void> will return 204 by default
undefinedResultCode: 204,

paramOptions: {
//with this option, argument will be required by default
required: true
Expand All @@ -822,6 +833,20 @@ const app = createExpressServer({
app.listen(3000);
```

#### Selectively disable request/response transform

To disable `class-transformer` on a per-controller or per-route basis, use the `transformRequest` and `transformResponse` options on your controller and route decorators:

```typescript
@Controller("/users", {transformRequest: false, transformResponse: false})
export class UserController {

@Get("/", {transformResponse: true}) {
// route option overrides controller option
}
}
```

## Using middlewares

You can use any existing express / koa middleware, or create your own.
Expand Down Expand Up @@ -1210,7 +1235,34 @@ If its a class - then instance of this class will be created.
This technique works with `@Body`, `@Param`, `@QueryParam`, `@BodyParam`, and other decorators.
Learn more about class-transformer and how to handle more complex object constructions [here][4].
This behaviour is enabled by default.
If you want to disable it simply pass `classTransformer: false` to createExpressServer method.
If you want to disable it simply pass `classTransformer: false` to createExpressServer method. Alternatively you can disable transforming for [individual controllers or routes](#selectively-disable-requestresponse-transforming).

## Controller Inheritance
Often your application may need to have an option to inherit controller from another to reuse code and void duplication.
A good example of the use is the CRUD operations which can be hidden inside `AbstractBaseController` with the possibility to add new and overload methods, the template method pattern.

```typescript
@Controller(`/product`)
class ProductController extends AbstractControllerTemplate {}
@Controller(`/category`)
class CategoryController extends AbstractControllerTemplate {}
abstract class AbstractControllerTemplate {
@Post()
public create() {}

@Read()
public read() {}

@Put()
public update() {}

@Delete()
public delete() {}
}

```
https://en.wikipedia.org/wiki/Template_method_pattern


## Auto validating action params

Expand Down Expand Up @@ -1264,7 +1316,7 @@ export class UserController {
}
```
If the param doesn't satisfy the requirements defined by class-validator decorators,
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.
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/typestack/class-validator#validation-errors) array.

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 })`.

Expand Down Expand Up @@ -1486,7 +1538,8 @@ export class QuestionController {
| `@Patch(route: string\|RegExp)` | `@Patch("/users/:id") patch()` | Methods marked with this decorator will register a request made with PATCH HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | `app.patch("/users/:id", patch)` |
| `@Delete(route: string\|RegExp)` | `@Delete("/users/:id") delete()` | Methods marked with this decorator will register a request made with DELETE HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | `app.delete("/users/:id", delete)` |
| `@Head(route: string\|RegExp)` | `@Head("/users/:id") head()` | Methods marked with this decorator will register a request made with HEAD HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | `app.head("/users/:id", head)` |
| `@Method(methodName: string, route: string\|RegExp)` | `@Method("move", "/users/:id") move()` | Methods marked with this decorator will register a request made with given `methodName` HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | `app.move("/users/:id", move)` |
| `@All(route: string\|RegExp)` | `@All("/users/me") rewrite()` | Methods marked with this decorator will register a request made with any HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | `app.all("/users/me", rewrite)` |
| `@Method(methodName: string, route: string\|RegExp)` | `@Method("move", "/users/:id") move()` | Methods marked with this decorator will register a request made with given `methodName` HTTP Method to a given route. In action options you can specify if action should response json or regular text response. | `app.move("/users/:id", move)` |

#### Method Parameter Decorators

Expand Down
Loading