-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.cjs.js
192 lines (164 loc) · 5.41 KB
/
client.cjs.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createClient = createClient;
/* eslint-disable */
exports.default = createClient;
function createClient(url, globalOptions = {}) {
if (typeof process === "undefined" && typeof window !== "undefined") {
window.process = {
env: {}
};
}
var client = async function fql(name, args, options = {}) {
if (!name) {
throw new Error("NAME_REQUIRED");
}
options.endpoint = globalOptions.endpoint = url;
if (globalOptions.connectionMode === "sockets") {
return executeBySocket.apply(this, [name, args, options, globalOptions]);
}
return await executeByHttp.apply(this, [name, args, options, globalOptions]);
};
return client;
}
function getSocket(scope = {}) {
const debug = getDebugInstance(`getSocket`, 4, scope);
debug('GET SOCKET??');
return new Promise((resolve, reject) => {
if (scope.socket && scope.socket.isActive === true) {
return scope.socket;
} else {
if (scope._isRetrievingSocket == true) {
let start = Date.now();
function checkSocketAvailable() {
if (scope.socket && scope.socket.isActive === true) {
resolve(scope.socket);
} else {
if (Date.now() - start > 1000 * 10) {
return reject("SOCKET_INIT_TIMEOUT");
}
setTimeout(() => checkSocketAvailable(), 20);
}
}
} else {
scope._isRetrievingSocket = true;
const io = scope.io = scope.io || require("socket.io-client");
const socket = scope.socket && scope.socket.on === true ? scope.socket : io(scope.endpoint);
socket.on("connect", function () {
socket.isActive = true;
scope.socket = socket;
scope._isRetrievingSocket = false;
debug("Adding socket", socket.id);
resolve(socket);
});
socket.on("disconnect", function () {
socket.isActive = false;
debug("Disposing socket", socket.id);
delete scope.socket;
});
}
}
});
}
function executeBySocket(name, args, options, globalOptions) {
const debug = getDebugInstance(`socket`, 4, globalOptions);
return new Promise(async (resolve, reject) => {
const elapsed = calculateElapsed();
const socket = await getSocket(globalOptions);
const request = { ...getRequestPayload(name, args, options, globalOptions),
id: require("uniqid")()
};
socket.once("fn_" + request.id, response => {
debug(name, elapsed(), {
request,
response
});
if (!!response.err) {
return response.reject(response, response.err);
}
resolve(response);
});
socket.emit("executeFunction", request);
});
}
function getRequestPayload(name, args = [], options = {}, globalOptions = {}) {
options.transform = !!options.transform && typeof options.transform !== "string" ? options.transform.toString() : options.transform;
const request = { ...options,
name: name,
args: args,
ns: options.namespace || options.ns || globalOptions.namespace || globalOptions.ns || process.env.VUE_APP_FUNQL_NAMESPACE || process.env.FUNQL_DEFAULT_NAMESPACE
};
return request;
}
async function executeByHttp(name, args = [], options = {}, globalOptions = {}) {
const debug = getDebugInstance(`http`, 4, globalOptions);
const endpoint = options.endpoint || process.env.VUE_APP_FUNQL_ENDPOINT || process.env.FUNQL_ENDPOINT;
const url = `${endpoint}/funql-api`;
const request = getRequestPayload(name, args, options, globalOptions);
const elapsed = calculateElapsed();
let fetchMethod = null;
if (typeof fetch !== 'undefined') {
fetchMethod = fetch;
} else {
const {
fetch
} = require('fetch-ponyfill')();
fetchMethod = fetch;
}
const rawResponse = await fetchMethod(`${url}?n=${name}&ns=${request.ns}`, {
method: "POST",
mode: "cors",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(request)
});
const response = await rawResponse.json();
debug(name, elapsed(), {
request,
response
});
if (response.err) {
response.err = typeof response.err === "object" ? JSON.stringify(response.err) : response.err;
throw new Error(response.err);
} else {
return response;
}
}
function calculateElapsed() {
var startDate = new Date();
return function () {
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
return seconds + "s";
};
}
function getDebugInstance(name, level = 4, options = {}) {
let levelLabel = {
1: "ERROR",
2: "WARN",
3: "INFO",
4: "DEBUG"
};
let debugEnv = parseInt(process.env.VUE_APP_DEBUG) || "funql*";
if (typeof window !== "undefined" && window.localStorage) {
localStorage.debug = (localStorage.debug || "") + `,${debugEnv}`;
}
let _level = parseInt(process.env.VUE_APP_DEBUG_LEVEL) || 4;
if (level > _level) {
return () => {};
} else {
let debug = () => {};
debug = options.debug || (typeof require !== "undefined" ? require("debug") : (prefix = "") => {
return function () {
let args = Array.prototype.slice.call(arguments);
args.unshift(prefix);
console.log.apply(this, args);
};
});
return debug(`${`fql-client:${name}`.padEnd(15, " ")} ${levelLabel[level].padEnd(7, " ")} ${`${Date.now()}`}`);
}
}