Request user decorator
An easier and safer way to extract the user from the request.
Notice that we are extracting the user directly from the request, which in turn is of type any. We'll create a decorator to directly access the user property from the request without having to access it directly, as is already done with @Body(), @Param(), @Query(), etc.
First, create the file auth/decorators/user.decorator. The contents of this file are mainly boilerplate for directly extracting something from the request. What we should really notice is the return at the end.
export const User = createParamDecorator(
(data: unknown, context: ExecutionContext) => {
const request = context.switchToHttp().getRequest<Request>();
return request.user;
},
);And we're done, now we can obtain the user from the request in a better way.
login(@User() user) {
return user;
}Commit - Creating decorator to extract user from request
However, the user itself still has the type any. We'll solve this in the next section.
Last updated