Created
October 26, 2016 02:38
-
-
Save sirgallifrey/aec1a34b7bf4d783d83c3114175d197e to your computer and use it in GitHub Desktop.
Hapijs - modifying responses with API calls
This file contains hidden or 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
'use strict'; | |
const Hapi = require('hapi'); | |
const server = new Hapi.Server(); | |
server.connection({ port: 3000 }); | |
// our route with normal output | |
server.route({ | |
path:'/', | |
method:'get', | |
handler: function (request, reply) { | |
const myData = [ | |
{ | |
'id': 1, | |
'email': '[email protected]' | |
}, | |
{ | |
'id': 2, | |
'email': '[email protected]' | |
} | |
]; | |
reply(myData); | |
} | |
}); | |
const checkForEmailsAPI = function (data) { | |
//here we can make our async API calls or something | |
//and return a promise, or you can use a callback if you want | |
//using promise.all to wait for an API call for every item on the list | |
return Promise.all(data.map((item) => { | |
//we are simulating an api call with promise.resolve | |
return Promise.resolve(Object.assign(item, { name: item.email.split('@')[0] })); | |
})); | |
} | |
server.ext('onPreResponse', function (request, reply) { | |
const response = request.response; | |
const myData = response.source; //the value provided using the reply interface. | |
//lets call our function that knows what to do with the data | |
checkForEmailsAPI(myData) | |
.then((newData) => { | |
//here is my new data, lets reply that | |
reply.continue(newData); | |
}); | |
}); | |
server.start((err) => { | |
if (err) { | |
throw err; | |
} | |
console.log(`server running at: ${server.info.uri}`); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment