How to prevent file upload if profile creation fails in NestJS using FileInterceptor?

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.

New contributor

kslmn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật