Skip to content

Commit 34cb2e4

Browse files
committed
Merge branch 'next' of https://github.com/pleerock/routing-controllers into next
2 parents 823155c + 6d7ce5f commit 34cb2e4

File tree

7 files changed

+153
-31
lines changed

7 files changed

+153
-31
lines changed

CHANGELOG.md

Lines changed: 81 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,63 @@
11
# Changelog and release notes
22

3-
### 0.8.0
3+
### 0.8.0 [BREAKING CHANGES]
4+
5+
#### Features
46

57
- extract generic `@Session()` deocorator into `@SessionParam()` and `@Session()`
6-
- restore/introduce `@QueryParams()` and `@Params()` missing decorators options (they are needed for validation purposes) - #289
7-
- normalize param object properties (for "queries", "headers", "params" and "cookies") - now you can easily validate query/path params using `class-validator` - #289
8-
- enhance params normalization - converting from string to primitive types is now more strict and can throw ParamNormalizationError,
9-
e.g. when number is expected but the invalid string (NaN) has been received - #289
8+
- restore/introduce `@QueryParams()` and `@Params()` missing decorators options (ref [#289][#289])
9+
- normalize param object properties (for "queries", "headers", "params" and "cookies"), with this change you can easily validate query/path params using `class-validator` (ref [#289][#289])
10+
- improved params normalization, converting to primitive types is now more strict and can throw ParamNormalizationError (e.g. when number is expected but an invalid string (NaN) has been received) (ref [#289][#289])
11+
12+
### 0.7.7 (to be released)
13+
14+
#### Features
15+
16+
- feat(ErrorHandling): add support for custom toJSON method in errors (ref [#325][#325])
17+
18+
#### Fixes
19+
20+
- fixed inconsistent roles parameter in authorizationChecker (ref [#308][#308])
21+
22+
### 0.7.6
23+
24+
#### Fixes
25+
26+
- fixed bugs with undefined result code behaviour
27+
28+
### 0.7.5
29+
30+
#### Fixes
31+
32+
- fixed bugs with undefined result code behaviour
33+
34+
### 0.7.4
35+
36+
#### Fixes
37+
38+
- fixed bugs with undefined result code behaviour
1039

1140
### 0.7.3
1241

13-
- FIXED: Directly calling response bug - #286
14-
- FIXED: Missing parameter in @BodyParam error message - #284
15-
- FIXED: Sync and async auth checker bug - #283
16-
- FIXED: Handling different content-type responses in JsonController - #277
17-
- ADDED: Support for returning Buffer and streams from action handler (controller's method) - #285
18-
- ADDED: Custom driver support - #276
42+
#### Features
43+
44+
- Support for returning Buffer and streams from action handler (controller's method) (ref [#285][#285])
45+
- Custom driver support (ref [#276][#276])
46+
47+
#### Fixes
48+
49+
- Directly calling response bug (ref [#286][#286])
50+
- Missing parameter in @BodyParam error message (ref [#284][#284])
51+
- Sync and async auth checker bug (ref (ref [#283][#283])
52+
- Handling different content-type responses in JsonController (ref [#277][#277])
1953

2054
### 0.7.2
2155

22-
- FIXED: Using `@Authorization` decorator with Koa caused 404 responses (ref [#240](https://github.com/pleerock/routing-controllers/pull/240))
23-
- FIXED: Allow throwing custom errors in `authorizationChecker` (ref [#233](https://github.com/pleerock/routing-controllers/pull/233), ref [#247](https://github.com/pleerock/routing-controllers/pull/247))
24-
- FIXED: check auth permissions before accepting files for upload (ref [#251](https://github.com/pleerock/routing-controllers/pull/240))
56+
#### Fixes
2557

26-
### 0.7.1
58+
- Using `@Authorization` decorator with Koa caused 404 responses (ref [#240][#240])
59+
- Allow throwing custom errors in `authorizationChecker` (ref [#233][#233])
60+
- check auth permissions before accepting files for upload (ref [#251][#251])
2761

2862
### 0.7.0 [BREAKING CHANGES]
2963

@@ -33,8 +67,7 @@ e.g. when number is expected but the invalid string (NaN) has been received - #2
3367
- `MiddlewareInterface` was removed and instead `ExpressMiddlewareInterface` or `KoaMiddlewareInterface` should be used
3468
- `ExpressErrorMiddlewareInterface` was renamed into `ErrorMiddlewareInterface`
3569
- per-controller and per-action middlewares used in `@UseBefore` and `@UseAfter` now should not be marked with `@Middleware` decorator
36-
- `@MiddlewareGlobalBefore()` and `@MiddlewareGlobalAfter()` were removed and instead new signatures should be used: `@Middleware({ type: "before" })`
37-
and `@Middleware({ type: "after" })`
70+
- `@MiddlewareGlobalBefore()` and `@MiddlewareGlobalAfter()` were removed and instead new signatures should be used: `@Middleware({ type: "before" })` and `@Middleware({ type: "after" })`
3871
- named some decorator parameter names
3972
- added few new decorators to get all parameters like `@QueryParams`, `@Params`, `@HeaderParams` etc.
4073
- added `@Authorized` and `@CurrentUser` decorators
@@ -50,29 +83,55 @@ and `@Middleware({ type: "after" })`
5083

5184
### 0.6.10
5285

53-
* added integration with `class-transform-validator` for deserialization and auto validation request parameters
86+
#### Features
87+
88+
- added integration with `class-transform-validator` for deserialization and auto validation request parameters
5489

5590
### 0.6.2
5691

57-
* made interceptors to support promises
92+
#### Features
93+
94+
- made interceptors to support promises
5895

5996
### 0.6.1
6097

98+
#### Features
99+
61100
- added interceptors support
62101

63102
### 0.6.0 [BREAKING CHANGES]
64103

104+
#### Features
105+
65106
- middleware and error handlers support
66107
- everything packed into "routing-controllers" main export
67-
- removed parseJson from @Body decorator
68-
- removed ActionOptions
69-
- removed responseType from action options and added @JsonResponse and @TextResponse decorators
70108
- added few more new decorators
109+
110+
#### Fixes
111+
71112
- fixed multiple issues with param decorators
72113
- fixed multiple bugs
73114
- refactored core
74115

116+
#### Removals
117+
118+
- removed `parseJson` from `@Body` decorator
119+
- removed `ActionOptions`
120+
- removed `responseType` from action options and added `@JsonResponse` and `@TextResponse` decorators
121+
75122
### 0.5.0
76123

77124
- renamed package from `controllers.ts` to `routing-controllers`
78125
- added integration with `constructor-utils` for serialization and deserialization
126+
127+
[#325]: https://github.com/pleerock/routing-controllers/pull/325
128+
[#308]: https://github.com/pleerock/routing-controllers/pull/308
129+
[#286]: https://github.com/pleerock/routing-controllers/pull/286
130+
[#285]: https://github.com/pleerock/routing-controllers/pull/285
131+
[#284]: https://github.com/pleerock/routing-controllers/pull/284
132+
[#283]: https://github.com/pleerock/routing-controllers/pull/283
133+
[#277]: https://github.com/pleerock/routing-controllers/pull/277
134+
[#276]: https://github.com/pleerock/routing-controllers/pull/276
135+
[#251]: https://github.com/pleerock/routing-controllers/pull/251
136+
[#240]: https://github.com/pleerock/routing-controllers/pull/240
137+
[#233]: https://github.com/pleerock/routing-controllers/pull/233

README.md

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,9 @@ import {useExpressServer} from "routing-controllers";
295295
let express = require("express"); // or you can import it if you have installed typings
296296
let app = express(); // your created express server
297297
// app.use() // you can configure it the way you want
298-
useExpressServer(app); // register created express server in routing-controllers
298+
useExpressServer(app, { // register created express server in routing-controllers
299+
controllers: [UserController] // and configure it the way you need (controllers, validation, etc.)
300+
});
299301
app.listen(3000); // run your express server
300302
```
301303

@@ -724,7 +726,30 @@ There are set of prepared errors you can use:
724726
* NotFoundError
725727
* UnauthorizedError
726728

727-
You can also create and use your own errors by extending `HttpError` class.
729+
730+
You can also create and use your own errors by extending `HttpError` class.
731+
To define the data returned to the client, you could define a toJSON method in your error.
732+
733+
```typescript
734+
class DbError extends HttpError {
735+
public operationName: string;
736+
public args: any[];
737+
738+
constructor(operationName: string, args: any[] = []) {
739+
super(500);
740+
Object.setPrototypeOf(this, DbError.prototype);
741+
this.operationName = operationName;
742+
this.args = args; // can be used for internal logging
743+
}
744+
745+
toJSON() {
746+
return {
747+
status: this.httpCode,
748+
failedOperation: this.operationName
749+
}
750+
}
751+
}
752+
```
728753

729754
#### Enable CORS
730755

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import {ExpressErrorMiddlewareInterface} from "../../src/driver/express/ExpressErrorMiddlewareInterface";
22
import {Middleware} from "../../src/decorator/Middleware";
33

4-
@Middleware({ type: "before" })
4+
@Middleware({ type: "after" })
55
export class AllErrorsHandler implements ExpressErrorMiddlewareInterface {
66

7-
error(error: any, request: any, response: any, next?: Function): void {
7+
error(error: any, request: any, response: any, next: Function): void {
88
console.log("Error handled: ", error);
99
next(error);
1010
}
1111

12-
}
12+
}

src/driver/BaseDriver.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,12 +150,14 @@ export abstract class BaseDriver {
150150
if (!this.isDefaultErrorHandlingEnabled)
151151
return error;
152152

153+
if (typeof error.toJSON === "function")
154+
return error.toJSON();
155+
153156
let processedError: any = {};
154157
if (error instanceof Error) {
155158
const name = error.name && error.name !== "Error" ? error.name : error.constructor.name;
159+
processedError.name = name;
156160

157-
if (name && (this.developmentMode || error.message)) // show name only if in debug mode and if error message exist too
158-
processedError.name = name;
159161
if (error.message)
160162
processedError.message = error.message;
161163
if (error.stack && this.developmentMode)

src/metadata/ActionMetadata.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ export class ActionMetadata {
207207
this.headers = this.buildHeaders(responseHandlers);
208208

209209
this.isAuthorizedUsed = this.controllerMetadata.isAuthorizedUsed || !!authorizedHandler;
210-
this.authorizedRoles = (this.controllerMetadata.authorizedRoles || []).concat(authorizedHandler && authorizedHandler.value ? authorizedHandler.value : []);
210+
this.authorizedRoles = (this.controllerMetadata.authorizedRoles || []).concat((authorizedHandler && authorizedHandler.value) || []);
211211
}
212212

213213
// -------------------------------------------------------------------------

src/metadata/ControllerMetadata.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ export class ControllerMetadata {
8686
build(responseHandlers: ResponseHandlerMetadata[]) {
8787
const authorizedHandler = responseHandlers.find(handler => handler.type === "authorized" && !handler.method);
8888
this.isAuthorizedUsed = !!authorizedHandler;
89-
this.authorizedRoles = authorizedHandler ? authorizedHandler.value : [];
89+
this.authorizedRoles = [].concat((authorizedHandler && authorizedHandler.value) || []);
9090
}
9191

9292
}

test/functional/express-error-handling.spec.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {Middleware} from "../../src/decorator/Middleware";
66
import {UseAfter} from "../../src/decorator/UseAfter";
77
import {ExpressErrorMiddlewareInterface} from "../../src/driver/express/ExpressErrorMiddlewareInterface";
88
import {NotFoundError} from "../../src/http-error/NotFoundError";
9+
import {HttpError} from "../../src/http-error/HttpError";
910
const chakram = require("chakram");
1011
const expect = chakram.expect;
1112

@@ -54,6 +55,25 @@ describe("express error handling", () => {
5455

5556
}
5657

58+
class ToJsonError extends HttpError {
59+
public publicData: string;
60+
public secretData: string;
61+
62+
constructor(httpCode: number, publicMsg?: string, privateMsg?: string) {
63+
super(httpCode);
64+
Object.setPrototypeOf(this, ToJsonError.prototype);
65+
this.publicData = publicMsg || "public";
66+
this.secretData = privateMsg || "secret";
67+
}
68+
69+
toJSON() {
70+
return {
71+
status: this.httpCode,
72+
publicData: `${this.publicData} (${this.httpCode})`
73+
}
74+
}
75+
}
76+
5777
@JsonController()
5878
class ExpressErrorHandlerController {
5979

@@ -97,6 +117,11 @@ describe("express error handling", () => {
97117
return "1234";
98118
}
99119

120+
@Get("/stories")
121+
stories() {
122+
throw new ToJsonError(503, "sorry, try it again later", "impatient user");
123+
}
124+
100125
}
101126
});
102127

@@ -154,4 +179,15 @@ describe("express error handling", () => {
154179
});
155180
});
156181

182+
it("should process JsonErrors by their toJSON method if it exists", () => {
183+
return chakram
184+
.get("http://127.0.0.1:3001/stories")
185+
.then((response: any) => {
186+
expect(response).to.have.status(503);
187+
expect(response.body).to.have.property("status").and.equals(503);
188+
expect(response.body).to.have.property("publicData").and.equals("sorry, try it again later (503)");
189+
expect(response.body).to.not.have.property("secretData");
190+
});
191+
});
192+
157193
});

0 commit comments

Comments
 (0)