TheRealToxicDev revisou este gist . Ir para a revisão
1 file changed, 62 insertions
uptime.js(arquivo criado)
@@ -0,0 +1,62 @@ | |||
1 | + | private _fetchURL() { | |
2 | + | const startPing: number = Date.now(); | |
3 | + | const timeout: Promise<Error> = new Promise((_, reject) => { | |
4 | + | setTimeout(() => { | |
5 | + | reject(new Error('timeout')) | |
6 | + | }, this.timeout); | |
7 | + | }); | |
8 | + | ||
9 | + | const fetchFunction = new Promise((resolve, reject) => { | |
10 | + | fetch(this.url, { headers: this.headers }) | |
11 | + | .then((res) => { | |
12 | + | resolve({ | |
13 | + | statusCode: res.status, | |
14 | + | statusText: res.statusText, | |
15 | + | ping: Date.now() - startPing | |
16 | + | }) | |
17 | + | }) | |
18 | + | .catch((e) => reject(e)); | |
19 | + | }); | |
20 | + | ||
21 | + | Promise.race([fetchFunction, timeout]) | |
22 | + | .then((result: any) => { | |
23 | + | this.ping = result.ping; | |
24 | + | ||
25 | + | if (result.statusCode > 299) { | |
26 | + | this.failures++; | |
27 | + | log.error(`[@infinitylist/uptime]: monitor failure: ${this.failures}`); | |
28 | + | ||
29 | + | if (this.failures > this.retries) { | |
30 | + | this._emitOutage(result.statusCode, result.statusText); | |
31 | + | } | |
32 | + | } else { | |
33 | + | ||
34 | + | this.failures = 0; | |
35 | + | this.available = true; | |
36 | + | this.uptime = Date.now() - this.startTime; | |
37 | + | this.lastSuccessCheck = Date.now(); | |
38 | + | ||
39 | + | this._emitUp(result.statusCode, result.statusText) | |
40 | + | } | |
41 | + | }) | |
42 | + | .catch((e) => { | |
43 | + | ||
44 | + | if (e.message.match('timeout')) { | |
45 | + | ||
46 | + | this.failures ++; | |
47 | + | log.error(`[@infinitylist/uptime]: monitor failure: ${this.failures}`); | |
48 | + | ||
49 | + | if (this.failures > this.retries) { | |
50 | + | this._emitOutage(undefined, 'timeout'); | |
51 | + | } | |
52 | + | } | |
53 | + | ||
54 | + | else { | |
55 | + | ||
56 | + | if (e.message.match('Only absolute URLs are supported')) return this.emit('error', TypeError('[@infinitylist/uptime]: only absolute urls are supported')); | |
57 | + | if (e.message.match('ECONNREFUSED')) return this.emit('error', TypeError(`[@infinitylist/client]: unknown host: ${this.url} connection refused`)); | |
58 | + | ||
59 | + | this.emit('error', e); | |
60 | + | } | |
61 | + | }) | |
62 | + | } |
Próximo
Anterior