-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathlib.js
60 lines (51 loc) · 1.41 KB
/
lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const net = require('net');
const http = require('http');
// Abstract Product Class
class ApiRequest {
makeGetRequest(url) {
return Error(`Implement make Get Request for ${url}`);
}
}
// Product A
class tcpApiRequest extends ApiRequest {
makeGetRequest(url) {
// Handling simple get request without query params
return new Promise((resolve, reject) => {
const socket = net.createConnection({
host: "www.example.com",
port: "80"
});
socket.on('data', (data) => resolve(data.toString()));
socket.on('error', err => reject(err));
socket.end(`GET / HTTP/1.1\r\nHost: ${url}\r\n\r\n`);
});
}
}
// Product B
class httpApiRequest extends ApiRequest {
makeGetRequest(url) {
// Handling simple get request without query params
return new Promise((resolve, reject) => {
http.request(`http://${url}`, (res) => {
res.on('data', data => resolve(data.toString()));
res.on('error', err => reject(err));
}).end();
});
}
}
/**
* This is an abstract factory interface. Uses a static function to
* generate family of products.
*/
class ApiRequestFactory {
static createApiRequest(kind) {
// This can easily be extended to include HTTPS, HTTP2, HTTP3
switch(kind) {
case "tcp":
return new tcpApiRequest();
case "http":
return new httpApiRequest();
}
}
}
module.exports = ApiRequestFactory;