Repository navigation
Expand file tree
/
Copy pathapp-router.js
More file actions
66 lines (63 loc) · 1.69 KB
/
Copy pathapp-router.js
File metadata and controls
66 lines (63 loc) · 1.69 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
const ajax = require('./utils/ajax');
const Cache = require('./cache');
function AppRouter(AV) {
this.AV = AV;
this.lockedUntil = 0;
Cache.getAsync('serverURLs')
.then(data => {
if (this.disabled) return;
if (!data) return this.lock(0);
const { serverURLs, lockedUntil } = data;
this.AV._setServerURLs(serverURLs, false);
this.lockedUntil = lockedUntil;
})
.catch(() => this.lock(0));
}
AppRouter.prototype.disable = function disable() {
this.disabled = true;
};
AppRouter.prototype.lock = function lock(ttl) {
this.lockedUntil = Date.now() + ttl;
};
AppRouter.prototype.refresh = function refresh() {
if (this.disabled) return;
if (Date.now() < this.lockedUntil) return;
this.lock(10);
const url = 'https://app-router.com/2/route';
return ajax({
method: 'get',
url,
query: {
appId: this.AV.applicationId,
},
})
.then(servers => {
if (this.disabled) return;
let ttl = servers.ttl;
if (!ttl) throw new Error('missing ttl');
ttl = ttl * 1000;
const protocal = 'https://';
const serverURLs = {
push: protocal + servers.push_server,
stats: protocal + servers.stats_server,
engine: protocal + servers.engine_server,
api: protocal + servers.api_server,
};
this.AV._setServerURLs(serverURLs, false);
this.lock(ttl);
return Cache.setAsync(
'serverURLs',
{
serverURLs,
lockedUntil: this.lockedUntil,
},
ttl
);
})
.catch(error => {
// bypass all errors
console.warn(`refresh server URLs failed: ${error.message}`);
this.lock(600);
});
};
module.exports = AppRouter;