Flatten nested promises
eliasmalik opened this issue · comments
Lines 35 to 56 in a84d27c
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.
- Use a
RETURNING
statement in thepostMemberInfo
function to retrieve the newly created user object without having to make an additional query. - 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.