Skip to content

Instantly share code, notes, and snippets.

@justsml
Last active April 9, 2020 12:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justsml/d6c9d8edadd0c1896f0b9ffb2c81a974 to your computer and use it in GitHub Desktop.
Save justsml/d6c9d8edadd0c1896f0b9ffb2c81a974 to your computer and use it in GitHub Desktop.
Functional River pattern
// 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