Skip to content

Commit ab0a5a6

Browse files
committed
Add api proxy/stub auto building
1 parent d9aacff commit ab0a5a6

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

JavaScript/5-api.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'use strict';
2+
3+
const http = require('http');
4+
5+
const ajax = (base, methods) => {
6+
const api = {};
7+
for (const method of methods) {
8+
api[method] = (...args) => {
9+
const callback = args.pop();
10+
const url = base + method + '/' + args.join('/');
11+
console.log(url);
12+
http.get(url, res => {
13+
if (res.statusCode !== 200) {
14+
callback(new Error(`Status Code: ${res.statusCode}`));
15+
return;
16+
}
17+
const lines = [];
18+
res.on('data', chunk => lines.push(chunk));
19+
res.on('end', () => callback(null, JSON.parse(lines.join())));
20+
});
21+
};
22+
}
23+
return api;
24+
};
25+
26+
// Usage
27+
28+
const api = ajax(
29+
'http://localhost:8000/api/',
30+
['user', 'userBorn']
31+
);
32+
33+
api.user('marcus', (err, data) => {
34+
if (err) throw err;
35+
console.dir({ data });
36+
});
37+
38+
api.userBorn('mao', (err, data) => {
39+
if (err) throw err;
40+
console.dir({ data });
41+
});

JavaScript/5-server.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict';
2+
3+
const http = require('http');
4+
5+
const users = {
6+
marcus: { name: 'Marcus Aurelius', city: 'Rome', born: 121 },
7+
mao: { name: 'Mao Zedong', city: 'Shaoshan', born: 1893 },
8+
};
9+
10+
const routing = {
11+
'/api/user/': name => users[name],
12+
'/api/userBorn/': name => users[name].born
13+
};
14+
15+
const types = {
16+
object: o => JSON.stringify(o),
17+
undefined: () => '{"error":"not found"}',
18+
function: (fn, req, res) => JSON.stringify(fn(req, res))
19+
};
20+
21+
http.createServer((req, res) => {
22+
const data = routing[req.url];
23+
const type = typeof(data);
24+
const serializer = types[type];
25+
const result = serializer(data, req, res);
26+
res.end(result);
27+
}).listen(8000);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy