-
Notifications
You must be signed in to change notification settings - Fork 0
/
APIClient_node.js
174 lines (166 loc) · 4.33 KB
/
APIClient_node.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
const http = require('http');
const https = require('https');
const Logger = require('log-ng');
const path = require('path');
const Governor = require('./Governor');
const interpolate = require('./interpolator');
const processPayload = require('./processPayload');
const logger = new Logger(path.basename(__filename));
/*
* A client object that is bound to a set of endpoints
*
* TODO:
* - cache busting
*/
function APIClientFactory(registry){
if(!new.target){
return new APIClientFactory(...arguments);
}
if(APIClientFactory.instance !== undefined){
return APIClientFactory.instance;
}
function getClient(protocol){
let client;
switch(protocol){
case 'http:':
client = http;
break;
case 'https:':
default:
client = https;
}
return client;
}
function httpHandler(entry, config){
try{
const options = {
...entry,
...config,
host: interpolate(entry.host, config),
path: interpolate(entry.path, config),
headers: interpolate(entry.headers, config)
};
logger.debug(JSON.stringify(options, null, 2));
const client = getClient(options.protocol);
return client.request(options, (res) => {
let response = '';
res.on('data', (chunk) => {response += chunk})
.on('end', () => {config.success(response)})
.on('error', config.failure)
.on('timeout', config.failure);
});
}catch(e){
logger.error(e);
config.failure(e);
}
}
const client = {
get: function(entry, config){
logger.debug('get call');
const req = httpHandler(entry, config);
req.end();
},
post: function(entry, config){
logger.debug('post call');
const req = httpHandler(entry, config);
const payload = processPayload(entry, config);
if(payload !== undefined){
req.write(payload);
}
req.end();
},
put: function(entry, config){
logger.debug('put call');
const req = httpHandler(entry, config);
const payload = processPayload(entry, config);
if(payload !== undefined){
req.write(payload);
}
req.end();
},
delete: function(entry, config){
logger.debug('delete call');
const req = httpHandler(entry, config);
req.end();
},
fetch: async function(entry, config){
logger.debug('fetch call');
const url = `${entry.protocol}//${entry.host}:${entry.port || '80'}${entry.path}`;
logger.debug(url);
try{
const response = await fetch(interpolate(url, config), {
method: entry.fetchMethod,
headers: Object.entries(entry.headers || {}).reduce((acc, [k, v]) => {
acc[k] = v;
return acc;
}, {}),
body: processPayload(entry, config)
});
config.success(response);
}catch(e){
logger.error(e);
logger.error(url);
config.failure(e);
}
},
custom: function(entry, config){
logger.debug('custom call');
const options = {
...entry,
...config,
method: entry.customMethod,
host: interpolate(entry.host, config),
path: interpolate(entry.path, config),
headers: interpolate(entry.headers, config)
};
const client = getClient(entry.protocol);
const req = client.request(options, (res) => {
let response = '';
res.on('data', (chunk) => {response += chunk})
.on('end', () => {config.success(response)})
.on('error', config.failure)
.on('timeout', config.failure);
});
const payload = processPayload(entry, config);
if(payload !== undefined){
req.write(payload);
}
req.end();
}
};
Object.entries(registry).forEach(([key, entry]) => {
if(entry.rate){
Governor(key, entry.rate, entry.period);
}
Object.defineProperty(this, key, {
enumerable: true,
value: function(config){
return new Promise((res, rej) => {
if(config.success === undefined){
config.success = (resp) => {
res(resp);
};
config.failure = (err) => {
rej(err);
};
}else{
res("Using provided callback");
}
if(Governor[key] === false){
const msg = `Call to ${key} throttled`;
logger.debug(msg);
config.failure(msg);
return;
}
logger.debug(`Call to ${key} not throttled`);
logger.debug(`Using entry:\n${JSON.stringify(entry, null, 2)}\nand config:\n${JSON.stringify(config, null, 2)}`);
client[entry.method].call(this, entry, config);
});
}
});
});
Object.defineProperty(APIClientFactory, "instance", {
value: this
});
};
module.exports = APIClientFactory;