Workflow for an Angular form that also includes a file upload – what to do in case of errors (MEAN stack)

0

I have an account creation form with an optional profile picture file upload. If the user submits (after validation), I need to store the profile picture (eventually S3 or another cloud service) and save the form data. However, if there is a problem with the file upload, then the account shouldn’t be created and data shouldn’t be stored in the database (including the file reference as the file isn’t saved). At the same time, if there is an error saving to the database, I don’t want to upload & store the image because it isn’t associated with any account since the account wasn’t saved. How is this typically handled? Right now, I have two services, one that uploads a file, and another that stores the data in mongodb, but both operate independently of one another.

This is what I was attempting to do, but realized isn’t going to work the way I need it to when there are errors from either service.

file-upload.service.ts

uploadFile(file: File) {
    return this.http.post(FILE_UPLOAD_ENDPOINT, file);
}

create-account.service.ts

createAccountService(account: any) {
    return this.http.post(CREATE_ACCCOUNT_ENDPOINT, account);
}

registration.component.ts

submitForm() {
    const createAccountService = this.authServices.createAccountService(this.registrationForm.value)
  
    let services = [createAccountService];
    if (this.profilePicFile) {
      const uploadFileService = this.utilServices.uploadFile(this.profilePicFile);
      services.push(uploadFileService);
    }
    return forkJoin(services).subscribe({
      next: (v) => {
        // Both are successful, now let's validate our email and log in.
      },
      error: (e) => {
        // At least one is unsuccessful, however we don't want to the other to have occurred due to one being unsuccessful, but at this point it is too late.
      }
    });
  }

I know this is a pretty common workflow, but this is my first time requiring both at once and I know there has to be a more intelligent way to do it. Any guidance would be greatly appreciated!