I’m working on a NestJS application where I need to handle file uploads using the FileInterceptor from @nestjs/platform-express. Specifically, I am building a profile creation route that accepts both form data and a profile picture. Here’s the relevant code:
Here is my controller
@Post('profile')
@Roles(Role.USER)
@UseInterceptors(
FileInterceptor('profilePicture', {
storage: diskStorage({
destination: PROFILE_UPLOAD_DIR,
filename: fileNameEditor,
}),
fileFilter: profileFilter,
limits: { fileSize: MAX_PROFILE_SIZE },
}),
)
async buildProfile(
@UploadedFile() profilePicture: Express.Multer.File,
@Body() body: any,
@GetCurrentUser('userId') userId: string,
) {
const dto: createProfileDto = body;
console.log(profilePicture);
const pathToProfile = uploads/profile/${profilePicture.filename};
const profile = await this.userService.buildProfile(
dto,
userId,
pathToProfile,
);
return { message: 'Successfully created Your profile', profile };
}
and here is my service
async buildProfile(
dto: createProfileDto,
userId: string,
profilePath: string,
) {
const {
phoneNumber,
firstName,
middleName,
lastName,
gender,
country,
city,
state,
} = dto;
console.log(profilePath);
// check if the profile already exists
const profile = await this.checkProfileExists(userId);
console.log(profile);
if (profile) throw new ConflictException('Profile already exists');
const bd = moment(dto.birthDate, 'DD/MM/YYYY');
const age = moment().diff(bd, 'years');
if (age < 13 && age > 100)
throw new BadRequestException(
'You must be between the age of 13 and 100 years old',
);
const newProfile = await this.prisma.profile.create({
data: {
userId,
phoneNumber,
firstName,
middleName,
lastName,
gender,
country,
state,
city,
birthDate: bd.toISOString(),
profilePicture: profilePath,
},
select: this.returnableFieldsProfile,
});
return newProfile;
}
async getProfile(id: string) {
const profile = await this.prisma.profile.findFirst({
where: { userId: id },
select: this.returnableFieldsProfile,
});
if (!profile) throw new NotFoundException('profile not found');
return profile;
}
The issue I’m facing is that the image file gets saved to the directory (uploads/profile) even if the profile creation fails due to reasons like the profile already existing or validation errors. This leads to unnecessary files being saved when the profile isn’t actually created.
I’ve tried to create some logic that check if the profile exists and then tried to add it to the multer options but it seems like i can’t use the this keyword inside the interceptor. therefore i cant add functions to the interceptor.
kslmn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.