-
Notifications
You must be signed in to change notification settings - Fork 0
/
stubify.js
42 lines (40 loc) · 1.35 KB
/
stubify.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
(root => {
const fetch = typeof window !== 'undefined' ? window.fetch : require ('node-fetch');
function stubify (server, objName, methods = []) {
let id = 1;
const proxy = new Proxy ({}, {
ownKeys : () => methods,
getOwnPropertyDescriptor : (target, prop) => ({
value : proxy[ prop ], writable : true, enumerable : true, configurable : true
}),
get : (() => {
const cache = [];
return (target, method) => {
return cache[ method ] || (cache[ method ] = async (...params) => {
const res = await fetch (`${ server }/${ objName }/`, {
method : 'POST',
headers : {'Content-Type' : 'application/json'},
body : JSON.stringify ({
jsonrpc : "2.0",
method : method,
params : params,
id : id++
}) // jsonRPC 2.0 standard format
});
const data = await res.json ();
if (res.status === 200) {
return data.result;
}
throw new Error (data.error.message);
});
};
}) ()
});
return proxy;
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = stubify
} else {
root.stubify = stubify;
}
}) (this);