diff --git a/JavaScript/5-api.js b/JavaScript/5-api.js new file mode 100644 index 0000000..a8fb98d --- /dev/null +++ b/JavaScript/5-api.js @@ -0,0 +1,41 @@ +'use strict'; + +const http = require('http'); + +const ajax = (base, methods) => { + const api = {}; + for (const method of methods) { + api[method] = (...args) => { + const callback = args.pop(); + const url = base + method + '/' + args.join('/'); + console.log(url); + http.get(url, res => { + if (res.statusCode !== 200) { + callback(new Error(`Status Code: ${res.statusCode}`)); + return; + } + const lines = []; + res.on('data', chunk => lines.push(chunk)); + res.on('end', () => callback(null, JSON.parse(lines.join()))); + }); + }; + } + return api; +}; + +// Usage + +const api = ajax( + 'http://localhost:8000/api/', + ['user', 'userBorn'] +); + +api.user('marcus', (err, data) => { + if (err) throw err; + console.dir({ data }); +}); + +api.userBorn('mao', (err, data) => { + if (err) throw err; + console.dir({ data }); +}); diff --git a/JavaScript/5-server.js b/JavaScript/5-server.js new file mode 100644 index 0000000..d033718 --- /dev/null +++ b/JavaScript/5-server.js @@ -0,0 +1,21 @@ +'use strict'; + +const http = require('http'); + +const users = { + marcus: { name: 'Marcus Aurelius', city: 'Rome', born: 121 }, + mao: { name: 'Mao Zedong', city: 'Shaoshan', born: 1893 }, +}; + +const routing = { + '/api/user': name => users[name], + '/api/userBorn': name => users[name].born +}; + +http.createServer((req, res) => { + const url = req.url.split('/'); + const par = url.pop(); + const method = routing[url.join('/')]; + const result = method ? method(par) : { error: 'not found' }; + res.end(JSON.stringify(result)); +}).listen(8000);