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;
  },
);

If you prefer, you can give a different name to this decorator, like CurrentUser or ActiveUser, to avoid importing the User entity by accident and vice-versa.

The Request type should be imported from express.

And we're done, now we can obtain the user from the request in a better way.

login(@User() user) {
  return user;
}

However, the user itself still has no type. We'll solve this in the next section.

Commit - Creating decorator to extract user from request

Last updated