Created
June 10, 2019 23:00
-
-
Save adamgall/821f4824634d3f812eb853c900fcbf3f to your computer and use it in GitHub Desktop.
i don't understand promises
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
export const register = (req, res) => { | |
const newUser = new User(res.locals.db)({ | |
name: req.body.name, | |
email: req.body.email, | |
password: req.body.password | |
}); | |
User(res.locals.db) | |
.findOne({ email: newUser.email }) | |
.then(checkDuplicateUser(res)) | |
.catch(makeError(409, res)) | |
.then(validateUser(newUser)) | |
.catch(makeError(400, res)) | |
.then(generatePassword(req.body.password)) | |
.catch(makeError(500, res)) | |
.then(saveWithPassword(newUser)) | |
.then(respond(res)) | |
.catch(() => {}); | |
}; | |
const makeError = (status, res) => { | |
return error => Promise.reject(res.status(status).json({error})); | |
} | |
const checkDuplicateUser = () => { | |
return user => { | |
return new Promise((resolve, reject) => { | |
if (!user) resolve(); | |
reject('email already exists'); | |
}); | |
} | |
} | |
export const validateUser = user => { | |
return () => { | |
return new Promise((resolve, reject) => { | |
if (!validateEmail(user.email)) | |
return reject('email invalid format'); | |
if (user.password.length < 8) | |
return reject('password must be >= 8 characters long'); | |
return resolve() | |
}); | |
}; | |
}; | |
export const generatePassword = password => { | |
return () => { | |
return new Promise((resolve, reject) => { | |
generateSalt(parseInt(process.env.BCRYPT_COST, 10)) | |
.then(salt => generateHash(salt, password)) | |
.then(resolve) | |
.catch(() => reject('password generation failed')); | |
}); | |
}; | |
}; | |
const saveWithPassword = (user) => { | |
return hash => { | |
user.password = hash; | |
return user.save(); | |
} | |
} | |
const respond = (res) => { | |
return user => res.json({ name: user.name, email: user.email }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment