diff --git a/src/decorators/user-roles.decorators.ts b/src/decorators/user-roles.decorators.ts index 369da39..2243d63 100644 --- a/src/decorators/user-roles.decorators.ts +++ b/src/decorators/user-roles.decorators.ts @@ -28,10 +28,14 @@ function userFactory(ctx: ExecutionContext): T { * * You can pass an optional property key to the decorator to get it from the user object * e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead. + * In case that the request is missing User object the function will return null */ -export const UserRoles = createParamDecorator( - (data: string, ctx: ExecutionContext) => { - const user = userFactory(ctx); - return data ? user[data] : user.roles; - }, -); +export const UserRoles = createParamDecorator< + string | undefined, + ExecutionContext, + (Role | string)[] | null +>((propertyKey: undefined | string, ctx: ExecutionContext) => { + const user = userFactory(ctx); + if (!user) return null; + return propertyKey ? user[propertyKey] : user.roles; +});