Skip to content

Instantly share code, notes, and snippets.

@sirgallifrey
Created October 26, 2016 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirgallifrey/aec1a34b7bf4d783d83c3114175d197e to your computer and use it in GitHub Desktop.
Save sirgallifrey/aec1a34b7bf4d783d83c3114175d197e to your computer and use it in GitHub Desktop.
Hapijs - modifying responses with API calls
'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': 'jdoe@bla.com'
},
{
'id': 2,
'email': 'jsmith@bla.com'
}
];
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