-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
51 lines (40 loc) · 1.21 KB
/
index.js
File metadata and controls
51 lines (40 loc) · 1.21 KB
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
const fetch = require('node-fetch');
const PREFIX = Symbol('prefix');
const ensureSuffix = (string, suffix) =>
string.endsWith(suffix) ? string : string + suffix;
const proxyHandler = {
get: (target, property) => createProxy([...target[PREFIX], property]),
apply: async (target, _this, arguments) =>
await callRemoteFunction(
target[PREFIX][0],
target[PREFIX].slice(1),
arguments
),
};
const createProxy = (prefix = []) => {
const f = () => {};
f[PREFIX] = prefix;
return new Proxy(f, proxyHandler);
};
const callRemoteFunction = async (apiEndpoint, functionPath, arguments) => {
const endpoint = apiEndpoint + functionPath.join('/');
const response = await fetch(endpoint, {
method: 'post',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify(arguments),
});
if (response.status === 404) {
throw new ReferenceError(`${functionPath.join('.')} is not defined`);
}
const text = await response.text();
if (response.status === 500) {
throw JSON.parse(text);
}
if (text.length > 0) {
return JSON.parse(text);
}
};
module.exports = ({ endpoint = '/' } = { endpoint: '/' }) =>
createProxy([ensureSuffix(endpoint, '/')]);