lundi 23 juillet 2018

Design Patterns for Performing Multiple Server Operations as a Single Transaction

Suppose you have a SaaS app and want to do the following when a user signs up:

  1. Validate their name, email etc.
  2. Create a Stripe Customer account for the user.
  3. Subscribe the new Stripe Customer to an existing Stripe Plan.
  4. Create a User record in your database which includes the Stripe info.
  5. Create a new session for the user.
  6. Redirect the user to your app's dashboard.

Ideally you want all these to happen in a single transaction, i.e if step 4 fails, you want to undo step 2 & 3...you don't want a dangling Stripe customer & subscription with no DB record.

What design patterns would you recommend to make such multi-step/multi-service process transactional?

For Context

I'm implementing this multi-step process using ES6 Promises in Node - pseudocode below:

async function signup_user_for_trial(req, res) {

  const {email, name, plan, password} = req.body

  if (!isValidEmail(email)) {
    throw new Error(...)
  }

  let customer = await createStripeCustomer(email)
  let subscription = await createSubscription(customer, plan)
  let user = await createDBUser(customer, name, email, password)
  let session = await createSession(req, user)

  return res.redirect('/dashboard')
}

Aucun commentaire:

Enregistrer un commentaire