Last active
September 4, 2018 12:59
-
-
Save macdonst/8f1e22947c04826c238df4d4e2b17424 to your computer and use it in GitHub Desktop.
Node server using Hapi.js
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 Joi = require('joi'); | |
const fetch = require('node-fetch'); | |
const credentials = require('./credentials'); | |
const server = Hapi.server({ | |
host: '0.0.0.0', | |
port: 8000 | |
}); | |
// Start the server | |
async function start() { | |
try { | |
await server.register(require('inert')); | |
server.route({ | |
method: 'POST', | |
path: '/wolfram', | |
config: { | |
handler: function(req) { | |
console.log('asking wolfram alpha'); | |
let url = `http://api.wolframalpha.com/v2/query?input=${ | |
req.payload.searchTerm | |
}&appid=${credentials.wolfram}`; | |
return fetch(url) | |
.then(res => res.text()) | |
.then(text => { | |
return text; | |
}); | |
}, | |
validate: { | |
payload: { | |
searchTerm: Joi.string().required() | |
} | |
} | |
} | |
}); | |
server.route({ | |
method: 'POST', | |
path: '/translate', | |
config: { | |
handler: function(req) { | |
console.log('POST translate'); | |
let url = `https://www.googleapis.com/language/translate/v2?key=${ | |
credentials.google | |
}&source=en&target=fr&q=${req.payload.searchTerm}`; | |
return fetch(url) | |
.then(res => res.json()) | |
.then(json => { | |
return json; | |
}); | |
}, | |
validate: { | |
payload: { | |
searchTerm: Joi.string().required() | |
} | |
} | |
} | |
}); | |
server.route({ | |
method: 'GET', | |
path: '/{param*}', | |
handler: { | |
directory: { | |
path: 'public' | |
} | |
} | |
}); | |
await server.start(); | |
} catch (err) { | |
console.log(err); | |
process.exit(1); | |
} | |
console.log('Server running at:', server.info.uri); | |
} | |
start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment