fac-13 / stackMatch

App to connect Founders & Coders members with each other 👌

Home Page:https://stackmatch-fac-dev.herokuapp.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Flatten nested promises

eliasmalik opened this issue · comments

commented

stackMatch/src/oauth.js

Lines 35 to 56 in a84d27c

checkOrgMembership(accessToken).then((res) => {
if (res === false) {
return next(null, false, { message: 'Not FAC member' });
} else {
return getMemberData(memberProfile.github_id)
.then((userDataObj) => {
if(!userDataObj){
postMemberInfo(memberProfile)
.then(() => {
getMemberData(memberProfile.github_id)
.then((newUserDataObj) => {
return next(null, newUserDataObj, { message: 'Signup successful' })
})
})
} else {
return next(null, userDataObj, { message: 'Login successful' })
}
})
}
})
.catch(error => { throw new Error(error.message) });
}),

You're not able to build a flat promise chain here because you want an early exit condition, and also have conditional logic to deal with signup/login, but making two changes can simplify things a bit.

  1. Use a RETURNING statement in the postMemberInfo function to retrieve the newly created user object without having to make an additional query.
  2. Create a custome error type to deal with the early exit condition.

Example:

class AuthenticationError extends Error {}

checkOrgMembership(accessToken)
  .then(isMember => {
    if (!isMember) {
      throw new AuthenticationError('Not a FAC member')
    }

    return getMemberData(memberProfile.github_id)
  })
  .then(user => 
    !user
      ? postMemberInfo(memberProfile).then(user => ({ user, message: 'Signup' }))
      : { user, message: 'Login' }
   )
  .then(({ user, message }) => next(null, user, message))
  .catch(err => {
    if (err instanceof AuthenticationError) {
      return next(null, false, { message: err.message })
    } else {
      return next(err)
    }
  })

I can understand if you don't find every element of the above example clearer than what you already have. Feel free to take what you like and leave the rest, though I would recommend adding the RETURNING statement as described above.