Skip to content

Commit 5b0b5b2

Browse files
committed
fix(user-decorator): add condition to prevent crash
1 parent 6a24cc8 commit 5b0b5b2

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

src/decorators/user-roles.decorators.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,14 @@ function userFactory<T>(ctx: ExecutionContext): T {
2828
*
2929
* You can pass an optional property key to the decorator to get it from the user object
3030
* e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead.
31+
* In case that the request is missing User object the function will return null
3132
*/
32-
export const UserRoles = createParamDecorator<string, ExecutionContext, (Role | string)[]>(
33-
(data: string, ctx: ExecutionContext) => {
34-
const user = userFactory<any>(ctx);
35-
return data ? user[data] : user.roles;
36-
},
37-
);
33+
export const UserRoles = createParamDecorator<
34+
string | undefined,
35+
ExecutionContext,
36+
(Role | string)[] | null
37+
>((propertyKey: undefined | string, ctx: ExecutionContext) => {
38+
const user = userFactory<any>(ctx);
39+
if (!user) return null;
40+
return propertyKey ? user[propertyKey] : user.roles;
41+
});

0 commit comments

Comments
 (0)