-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (44 loc) · 1.22 KB
/
index.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
const https = require('https')
const getParsedAuthcode = require('./source-parser/getAuthcode.js')
const AbortController = require('abort-controller')
const URL = 'https://raw.githubusercontent.com/simplyGits/magisterjs-authcode/master/code.json'
const req = function (timeout) {
return new Promise((resolve, reject) => {
const rej = msg => reject(new Error(msg))
const request = https.get(URL, res => {
const { statusCode } = res
if (statusCode !== 200) {
rej(`invalid statusCode: ${statusCode}`)
res.resume()
return
}
res.setEncoding('utf8')
let buf = ''
res.on('data', blob => buf += blob)
res.on('end', () => {
try {
const parsed = JSON.parse(buf)
resolve(parsed)
} catch (e) {
reject(e)
}
})
})
request.setTimeout(timeout, () => rej('timeout hit'))
})
}
async function getAuthcodeFromNet(timeout) {
const controller = new AbortController()
const handle = setTimeout(
() => controller.abort(),
timeout,
)
const res = await getParsedAuthcode(controller.signal)
clearTimeout(handle)
return res
}
module.exports = function (timeout = 1500) {
return getAuthcodeFromNet(timeout)
.catch(() => req(timeout))
.catch(() => require('@magisterjs/authcode'))
}