-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
112 lines (99 loc) · 2.72 KB
/
client.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
var fetchJSON = require("./fetchJSON");
function handleResponse(response) {
if (response.success) {
return response.result;
} else {
var error = new Error();
for (var key in response.err) {
if ({}.hasOwnProperty.call(response.err, key)) {
Object.defineProperty(error, key, {
writable: true,
enumerable: false,
configurable: true,
value: response.err[key],
});
}
}
throw error;
}
}
module.exports = function createClient(config) {
if (
typeof config !== "object" ||
config == null ||
typeof config.url !== "string"
) {
throw new Error(
"Invalid config provided to createClient. You must provide an object with, at minimum, a `url` key, which is a string."
);
}
var clientObj = {};
if (config.methods != null) {
config.methods.forEach(function(methodName) {
function doRequest() {
return fetchJSON(
"POST",
config.url,
{
methodName,
args: [].slice.call(arguments),
},
false,
config.timeout
).then(handleResponse);
}
doRequest.sync = function doRequestSync() {
return handleResponse(
fetchJSON(
"POST",
config.url,
{
methodName,
args: [].slice.call(arguments),
},
true,
config.timeout
)
);
};
Object.defineProperty(doRequest, "name", { value: methodName });
Object.defineProperty(doRequest.sync, "name", {
value: methodName + ".sync",
});
clientObj[methodName] = doRequest;
});
}
const socketUrl = config.url
.replace(/^http:/, "ws:")
.replace(/^https:/, "wss:");
if (config.socketMethods != null) {
config.socketMethods.forEach(function(methodName) {
function openSocket() {
var socket = new WebSocket(
socketUrl +
"/" +
btoa(
JSON.stringify({
methodName,
args: [].slice.call(arguments),
})
)
);
socket.onclose = function onclose(event) {
var message =
"Socket closed: " + (event.reason || "Code " + event.code);
// Log close messages by default to provide a better UX. This can be overridden.
if (event.code === 4500 || event.code === 4404) {
console.error(new Error(message));
} else {
console.warn(message);
}
};
return socket;
}
Object.defineProperty(openSocket, "name", { value: methodName });
clientObj[methodName] = openSocket;
});
}
return clientObj;
};