|
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.
- Use a
RETURNING statement in the postMemberInfo 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.
stackMatch/src/oauth.js
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.
RETURNINGstatement in thepostMemberInfofunction to retrieve the newly created user object without having to make an additional query.Example:
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
RETURNINGstatement as described above.