Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions JavaScript/5-api.js
Original file line number Diff line number Diff line change
@@ -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 });
});
21 changes: 21 additions & 0 deletions JavaScript/5-server.js
Original file line number Diff line number Diff line change
@@ -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);