Last active
November 10, 2018 03:06
-
-
Save justsml/b2b43996ceca11e037b3939f27d8157d to your computer and use it in GitHub Desktop.
Using Functional Promises library
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 FP = require('functional-promises') | |
const {hashString} = require('./lib/crypto') | |
const users = require('./lib/users') | |
function auth({username = '', password = ''}) { | |
return FP | |
.resolve({username, password}) | |
.then(_checkArgs) | |
.then(_loginUser) | |
.then(_checkUser) | |
.thenIf( | |
user => user.admin, | |
user => _loadAdmin(user)) | |
} | |
// You could still use async/await here - tiny functions are the key: | |
async function _loadAdmin(user) { | |
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