Attach user id from access token using DTO

Viewed 715

I create POST endpoint to create a new entity. I also created schema for mongoose with field userId (to connect this entity to specified user) and DTO which I use on my POST method.

@UseGuards(JwtAuthGuard)
@Post("/")
createAction(@Request() req, @Body() createActionDto: CreateActionDto) {
    return this.actionService.createAction(req?.user?.userId, createActionDto);
}

DTO:

import { IsString, IsNumber, IsUrl } from 'class-validator';

export class CreateActionDto {
    userId: string;

    @IsString()
    name: string;

    @IsNumber()
    timeStart: number;
}

Schema:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Action extends Document {
    @Prop()
    userId: string;

    @Prop()
    name: string;

    @Prop()
    timeStart: number;
}

export const ActionSchema = SchemaFactory.createForClass(Action)

In the req property I have userId. What is the best way to create an entity and attach userId extracted from token?

Should I pass req to the service, and in the service set userId property on DTO like this?:

@Injectable()
export class ActionService {
    constructor(
        @InjectModel(Action.name) private actionModel: Model<Action>,
    ) { }

    async createAction(req: string, createActionDto: CreateActionDto) {
        createActionDto.userId = req.user.userId

        // ... save to mongoose createActionDto
    }
}

Is it a correct solution or there is another, a better way to deal with it?

1 Answers

Personally I would set the userId in the controller in order to not having to pass it around:

@UseGuards(JwtAuthGuard)
@Post("/")
createAction(@Request() req, @Body() createActionDto: CreateActionDto) {
    createActionDto.userId = req?.user?.userId;
    return this.actionService.createAction(createActionDto);
}

If you have many different controllers and DTOs that require the userId you could also define an Interceptor and do it there in order to reduce duplication:

@Injectable()
export class SetUserIdInterceptor implements NestInterceptor {
  public intercept(_context: ExecutionContext, $next: CallHandler): Observable<any> {    
   const request: any = _context.switchToHttp().getRequest(); //instead of any you could also define a super-class for all DTOs that require the `userId`-property    
   request.body?.userId = req?.user?.userId;
   return $next;
  }
}

You can then use this interceptor on your route as follows:

@UseGuards(JwtAuthGuard)
@Post("/")
@UseInterceptors(SetUserIdInterceptor)
createAction(@Body() createActionDto: CreateActionDto) {
    return this.actionService.createAction(createActionDto)
}
Related