Skip to content

Commit 0e91408

Browse files
committed
Refactor part of @Session decorator to @SessionParam
1 parent 34ac8ac commit 0e91408

File tree

9 files changed

+56
-43
lines changed

9 files changed

+56
-43
lines changed

CHANGELOG.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22

33
### 0.8.0
44

5-
- restore/introduce `@QueryParams()` and `@Params()` missing decorators options (they are needed for validation purposes) (#289)
6-
- normalize param object properties (for "queries", "headers", "params" and "cookies") - now you can easily validate query/path params using `class-validator` (#289)
5+
- 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
78
- enhance params normalization - converting from string to primitive types is now more strict and can throw ParamNormalizationError,
8-
e.g. when number is expected but the invalid string (NaN) has been received (#289)
9+
e.g. when number is expected but the invalid string (NaN) has been received - #289
910

1011
### 0.7.3
1112

README.md

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -450,18 +450,20 @@ If you want to inject all header parameters use `@CookieParams()` decorator.
450450

451451
#### Inject session object
452452

453-
To inject a session value, use `@Session` decorator:
453+
To inject a session value, use `@SessionParam` decorator:
454454

455455
```typescript
456-
@Get("/login/")
457-
savePost(@Session("user") user: User, @Body() post: Post) {
458-
}
456+
@Get("/login")
457+
savePost(@SessionParam("user") user: User, @Body() post: Post) {}
459458
```
460459
If you want to inject the main session object, use `@Session()` without any parameters.
461-
460+
```typescript
461+
@Get("/login")
462+
savePost(@Session() session: any, @Body() post: Post) {}
463+
```
462464
The parameter marked with `@Session` decorator is required by default. If your action param is optional, you have to mark it as not required:
463465
```ts
464-
action(@Session("user", { required: false }) user: User)
466+
action(@Session("user", { required: false }) user: User) {}
465467
```
466468

467469
Express uses [express-session][5] / Koa uses [koa-session][6] or [koa-generic-session][7] to handle session, so firstly you have to install it manually to use `@Session` decorator.
@@ -1430,14 +1432,15 @@ export class QuestionController {
14301432
| `@Res()` | `getAll(@Res() response: Response)` | Injects a Response object. | `function (request, response)` |
14311433
| `@Ctx()` | `getAll(@Ctx() context: Context)` | Injects a Context object (koa-specific) | `function (ctx)` (koa-analogue) |
14321434
| `@Param(name: string, options?: ParamOptions)` | `get(@Param("id") id: number)` | Injects a router parameter. | `request.params.id` |
1433-
| `@Params()` | `get(@Params() params: any)` | Injects all request parameters. | `request.params` |
1435+
| `@Params()` | `get(@Params() params: any)` | Injects all router parameters. | `request.params` |
14341436
| `@QueryParam(name: string, options?: ParamOptions)` | `get(@QueryParam("id") id: number)` | Injects a query string parameter. | `request.query.id` |
14351437
| `@QueryParams()` | `get(@QueryParams() params: any)` | Injects all query parameters. | `request.query` |
14361438
| `@HeaderParam(name: string, options?: ParamOptions)` | `get(@HeaderParam("token") token: string)` | Injects a specific request headers. | `request.headers.token` |
14371439
| `@HeaderParams()` | `get(@HeaderParams() params: any)` | Injects all request headers. | `request.headers` |
14381440
| `@CookieParam(name: string, options?: ParamOptions)` | `get(@CookieParam("username") username: string)` | Injects a cookie parameter. | `request.cookie("username")` |
1439-
| `@CookieParams()` | `get(@CookieParams() params: any)` | Injects all cookies. | `request.cookies |
1440-
| `@Session(name?: string)` | `get(@Session("user") user: User)` | Injects an object from session (or the whole session). | `request.session.user` |
1441+
| `@CookieParams()` | `get(@CookieParams() params: any)` | Injects all cookies. | `request.cookies` |
1442+
| `@Session()` | `get(@Session() session: any)` | Injects the whole session object. | `request.session` |
1443+
| `@SessionParam(name: string)` | `get(@SessionParam("user") user: User)` | Injects an object from session property. | `request.session.user` |
14411444
| `@State(name?: string)` | `get(@State() session: StateType)` | Injects an object from the state (or the whole state). | `ctx.state` (koa-analogue) |
14421445
| `@Body(options?: BodyOptions)` | `post(@Body() body: any)` | Injects a body. In parameter options you can specify body parser middleware options. | `request.body` |
14431446
| `@BodyParam(name: string, options?: ParamOptions)` | `post(@BodyParam("name") name: string)` | Injects a body parameter. | `request.body.name` |

sample/sample12-session-support/UserController.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {Patch} from "../../src/decorator/Patch";
99
import {Delete} from "../../src/decorator/Delete";
1010
import {Param} from "../../src/decorator/Param";
1111
import {Session} from "../../src/decorator/Session";
12+
import {SessionParam} from "../../src/decorator/SessionParam";
1213
import {ContentType} from "../../src/decorator/ContentType";
1314

1415
@Controller()
@@ -25,7 +26,7 @@ export class UserController {
2526

2627
@Get("/users/:id")
2728
@ContentType("application/json")
28-
getOne(@Session("user") user: any) {
29+
getOne(@SessionParam("user") user: any) {
2930
return user;
3031
}
3132

src/decorator/Session.ts

Lines changed: 4 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,34 +5,17 @@ import { getMetadataArgsStorage } from "../index";
55
* Injects a Session object to the controller action parameter.
66
* Must be applied on a controller action parameter.
77
*/
8-
export function Session(options?: ParamOptions): ParameterDecorator;
9-
/**
10-
* Injects a Session object to the controller action parameter.
11-
* Must be applied on a controller action parameter.
12-
*/
13-
export function Session(propertyName: string, options?: ParamOptions): ParameterDecorator;
14-
15-
export function Session(optionsOrObjectName?: ParamOptions|string, paramOptions?: ParamOptions): ParameterDecorator {
16-
let propertyName: string|undefined;
17-
let options: ParamOptions|undefined;
18-
if (typeof optionsOrObjectName === "string") {
19-
propertyName = optionsOrObjectName;
20-
options = paramOptions || {};
21-
} else {
22-
options = optionsOrObjectName || {};
23-
}
24-
8+
export function Session(options?: ParamOptions): ParameterDecorator {
259
return function (object: Object, methodName: string, index: number) {
2610
getMetadataArgsStorage().params.push({
2711
type: "session",
2812
object: object,
2913
method: methodName,
3014
index: index,
31-
name: propertyName,
3215
parse: false, // it makes no sense for Session object to be parsed as json
33-
required: options.required !== undefined ? options.required : true,
34-
classTransform: options.transform,
35-
validate: options.validate !== undefined ? options.validate : false,
16+
required: options && options.required !== undefined ? options.required : true,
17+
classTransform: options && options.transform,
18+
validate: options && options.validate !== undefined ? options.validate : false,
3619
});
3720
};
3821
}

src/decorator/SessionParam.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { ParamOptions } from "../decorator-options/ParamOptions";
2+
import { getMetadataArgsStorage } from "../index";
3+
4+
/**
5+
* Injects a Session object property to the controller action parameter.
6+
* Must be applied on a controller action parameter.
7+
*/
8+
export function SessionParam(propertyName: string, options?: ParamOptions): ParameterDecorator {
9+
return function (object: Object, methodName: string, index: number) {
10+
getMetadataArgsStorage().params.push({
11+
type: "session-param",
12+
object: object,
13+
method: methodName,
14+
index: index,
15+
name: propertyName,
16+
parse: false, // it makes no sense for Session object to be parsed as json
17+
required: options && options.required !== undefined ? options.required : false,
18+
classTransform: options && options.transform,
19+
validate: options && options.validate !== undefined ? options.validate : false,
20+
});
21+
};
22+
}

src/driver/express/ExpressDriver.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -195,10 +195,10 @@ export class ExpressDriver extends BaseDriver {
195195
case "params":
196196
return request.params;
197197

198+
case "session-param":
199+
return request.session[param.name];
200+
198201
case "session":
199-
if (param.name)
200-
return request.session[param.name];
201-
202202
return request.session;
203203

204204
case "state":

src/driver/koa/KoaDriver.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,10 +170,11 @@ export class KoaDriver extends BaseDriver {
170170
return context.params;
171171

172172
case "session":
173-
if (param.name)
174-
return context.session[param.name];
175173
return context.session;
176174

175+
case "session-param":
176+
return context.session[param.name];
177+
177178
case "state":
178179
if (param.name)
179180
return context.state[param.name];

src/metadata/types/ParamType.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ export type ParamType = "body"
1212
|"param"
1313
|"params"
1414
|"session"
15+
|"session-param"
1516
|"state"
1617
|"cookie"
1718
|"cookies"

test/functional/action-params.spec.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {Param} from "../../src/decorator/Param";
1313
import {Post} from "../../src/decorator/Post";
1414
import {UseBefore} from "../../src/decorator/UseBefore";
1515
import {Session} from "../../src/decorator/Session";
16+
import {SessionParam} from "../../src/decorator/SessionParam";
1617
import {State} from "../../src/decorator/State";
1718
import {QueryParam} from "../../src/decorator/QueryParam";
1819
import {QueryParams} from "../../src/decorator/QueryParams";
@@ -156,27 +157,27 @@ describe("action parameters", () => {
156157

157158
@Get("/session/")
158159
@UseBefore(SessionMiddleware)
159-
loadFromSession(@Session("testElement") testElement: string) {
160+
loadFromSession(@SessionParam("testElement") testElement: string) {
160161
sessionTestElement = testElement;
161162
return `<html><body>${testElement}</body></html>`;
162163
}
163164

164165
@Get("/not-use-session/")
165-
notUseSession(@Session("testElement") testElement: string) {
166+
notUseSession(@SessionParam("testElement") testElement: string) {
166167
sessionTestElement = testElement;
167168
return `<html><body>${testElement}</body></html>`;
168169
}
169170

170171
@Get("/session-param-empty/")
171172
@UseBefore(SessionMiddleware)
172-
loadEmptyParamFromSession(@Session("empty", { required: false }) emptyElement: string) {
173+
loadEmptyParamFromSession(@SessionParam("empty", { required: false }) emptyElement: string) {
173174
sessionTestElement = emptyElement;
174175
return `<html><body>${emptyElement === undefined}</body></html>`;
175176
}
176177

177178
@Get("/session-param-empty-error/")
178179
@UseBefore(SessionMiddleware)
179-
errorOnLoadEmptyParamFromSession(@Session("empty") emptyElement: string) {
180+
errorOnLoadEmptyParamFromSession(@SessionParam("empty") emptyElement: string) {
180181
sessionTestElement = emptyElement;
181182
return `<html><body>${emptyElement === undefined}</body></html>`;
182183
}

0 commit comments

Comments
 (0)