Repository navigation
Expand file tree
/
Copy pathfreshPublicIP.js
More file actions
85 lines (66 loc) · 1.78 KB
/
Copy pathfreshPublicIP.js
File metadata and controls
85 lines (66 loc) · 1.78 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
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
'use strict';
const EventEmitter = require('events');
const publicIP = require('public-ip');
const DEFAULT_OPTIONS = {
autoRefresh : true,
minRefreshInterval: 60000
};
class FreshPublicIP extends EventEmitter {
constructor(options = DEFAULT_OPTIONS) {
super();
this.busy = false;
this.disposed = false;
this.options = Object.assign({}, DEFAULT_OPTIONS, options);
this.options.autoRefresh && this.refresh();
}
dispose() {
this.disposed = true;
this._clearSchedule();
}
address() {
return this._promise;
}
autoRefresh(enabled) {
if (enabled) {
this.options.autoRefresh = true;
this._schedule();
} else {
this.options.autoRefresh = false;
this._clearSchedule();
}
}
refresh() {
if (!this.busy) {
this.busy = true;
this._promise = publicIP.v4().then(
address => {
this.busy = false;
this.lastRefresh = Date.now();
this.options.autoRefresh && !this.disposed && this._schedule();
this.emit('update', address);
return address;
},
err => {
this.busy = false;
this.lastRefresh = Date.now();
this.options.autoRefresh && !this.disposed && this._schedule();
return Promise.reject(err);
}
);
}
return this._promise;
}
_clearSchedule() {
clearTimeout(this._scheduled);
}
_schedule() {
const nextRefreshAt = (this.lastRefresh || 0) + this.options.minRefreshInterval;
const timeToNextRefresh = Math.max(0, nextRefreshAt - Date.now());
this._clearSchedule();
this._scheduled = setTimeout(() => {
this._scheduled = null;
this.refresh();
}, timeToNextRefresh);
}
}
module.exports = options => new FreshPublicIP(options);