-
-
Save yandongxu/2a583e2e7ef3054b43c1 to your computer and use it in GitHub Desktop.
How to use ES6 generators with Hapi.js <3
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
import co from 'co' | |
// Generator controller, | |
// this.models refers to Sequelize models added with server.bind() | |
function* loginController(request) { | |
let user = yield this.models.User.find({ | |
where: { | |
email: request.payload.email | |
} | |
}); | |
if (!user) | |
yield Promise.reject(Boom.notFound('USER_NOT_FOUND')); | |
return user.toJSON(); | |
} | |
// Wraps generator so it can be used in Hapi responses | |
function wrapGen(generator) { | |
let handler = co.wrap(generator); | |
return function(request, reply) { | |
handler.bind(this)(request, reply) | |
.then(reply) | |
.catch(reply); | |
}; | |
} | |
// Here's the most typical Hapi.js route | |
server.route({ | |
method: 'POST', | |
path: '/auth/login', | |
handler: wrapGen(loginController) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment