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?