Last active
July 28, 2016 12:00
-
-
Save hendrikniemann/02c12c72657f301900b3 to your computer and use it in GitHub Desktop.
Webservice Aggregator for foaas.com and randomuser.me
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 express = require('express'); | |
| const request = require('request-promise'); | |
| const FOAAS_URL = 'http://foaas.com/'; | |
| const RANDOM_URL = 'http://api.randomuser.me/'; | |
| const logError = console.log.bind( console ); | |
| function encodeName(a, b) { | |
| return capital(a) + '%20' + capital(b); | |
| function capital( str ) { | |
| return str.charAt(0).toUpperCase() + str.slice(1); | |
| } | |
| } | |
| const api = express(); | |
| api.get('/api/:type', (req, res) => { | |
| const type = req.params.type; | |
| if(!req.types.has(type)) { | |
| return res.sendStatus(404); | |
| } | |
| const numNames = req.types.get(type); | |
| request(RANDOM_URL + '?results=' + numNames ) | |
| .then(JSON.parse) | |
| .then(res => res.results.map(result => encodeName(result.user.name.first, result.user.name.last ))) | |
| .then(names => names.reduce((p, c) => p + '/' + c , '')) | |
| .then(addition => request(FOAAS_URL + type + addition)) | |
| .then(res.send.bind(res)) | |
| .catch(logError); | |
| }); | |
| request(FOAAS_URL + 'operations') | |
| .then(JSON.parse ) | |
| .then(data => { | |
| const types = new Map(); | |
| for (let i = 0; i < data.length; i++) { | |
| types.set(data[i].url.match(/^\/([a-z\-]+)(\/|$)/)[1], data[i].fields.length); | |
| } | |
| return types; | |
| }) | |
| .then(types => { | |
| const app = express(); | |
| app.use((req, res, next) => { | |
| req.types = types; | |
| next(); | |
| }); | |
| app.use(api); | |
| app.listen(3000); | |
| }) | |
| .catch( logError ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment