Search code examples
javascriptnode.jsreactjsexpressapi-design

How to handle an interruption in a form submit that's persisting data into the database?


I'm handling user signups with two endpoints, one that creates a user, and another one that creates a user_file. The user_file table holds a referrence to the user table. The function to handle the form being submitted looks like this:

  const onSubmit = async () => {
    // 1. create a user
    let response = await axios.post('/users', userData);

    // the id of the newly created user (we need it for the next steps)
    let userId = response.data.id;

    // 2. create a user file for the newly created user, type profile image
    await axios.post(`/userfile?type=avatar&userId=${userId}`, profileImageFile);

    // 3. create a file for the newly created user, type cv
    await axios.post(`/userfile?type=cv&userId=${userId}`, cvFile);
  }

If something happens between the steps, I'll have incomplete data, for example: a user clicks on "submit" but he leaves the page early while the backend was uploading his profile image, meaning that the user register was created, but none of the files were, leaving the database with an "incomplete" user.

Is there something I can do to make sure that all records are created? Since I need the user's id to upload the files I know this would be a tricky question, since it'd require to undo something that was done in the database, but I'm curious if you guys have encountered this issue and how you would go on about solving it.

NOTE: I'm currently facing this problem in an app that requires you to upload multiple files at signup, so the risk of getting incomplete data is greater and I've come across a couple of instances of users that had bad connectivity and were created without some of the files. I'm using MySQL for the database


Solution

    1. i would merge those 3 requests into 1. that way nothing would be able to be incomplete.

    2. another solution would be to have a boolean indication that the user is "full", and this boolean is only set when all 3 actions are done. that way you can use a cron to delete incomplete users or use whatever other treatment.

    ps: what is the real problem about an incomplete user ? just let the retry when they want. you can even email them to remind them to do so.