Last active
April 9, 2020 12:29
-
-
Save justsml/d6c9d8edadd0c1896f0b9ffb2c81a974 to your computer and use it in GitHub Desktop.
Functional River pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Functional River Pattern | |
// Original: https://github.com/justsml/escape-from-callback-mountain/blob/master/src/auth.fp.js | |
const {hashString} = require('./lib/crypto') | |
const users = require('./lib/users') | |
function auth({username = '', password = ''}) { | |
return Promise.resolve({username, password}) | |
.then(_checkArgs) | |
.then(_loginUser) | |
.then(_checkUser) | |
.then(_loadAdmin) | |
} | |
// You could still use async/await here - tiny functions are the key: | |
async function _loadAdmin(user) { | |
if (user.admin) { | |
const admin = await admin.findOneAsync({ id: user.id }); | |
user.adminPermissions = admin.permissions; | |
} | |
return user; | |
} | |
function _checkArgs({username = '', password = ''}) { | |
if (username.length < 1) throw new Error('Enter valid username') | |
if (password.length < 6) throw new Error('Enter valid Password') | |
return {username, password} | |
} | |
function _loginUser({username, password}) { | |
return Promise.resolve(password) | |
.then(hashString) | |
.then(password => users.getOne({username, password})) | |
} | |
function _checkUser(user) { | |
if (user && user._id) return user | |
throw new Error('No User found. Check credentials and try again.') | |
} | |
module.exports = {auth, _checkArgs, _loginUser, _checkUser} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment