generated from Lidemy/mentor-program-5th
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchallenge.js
87 lines (75 loc) · 2.07 KB
/
challenge.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
const https = require('https')
const BATCH_LIMIT = 100
const TOTAL = 200
function sendRequest(option, callback) {
const chunks = []
// console.log('option: ', option)
// console.log('callback: ', callback)
const req = https.request(option, (res) => {
res.on('data', (d) => {
chunks.push(d)
})
res.on('end', () => {
try {
const body = JSON.parse(Buffer.concat(chunks))
callback(body)
} catch (err) {
console.error(err)
}
})
})
req.on('error', (err) => {
console.error(err)
})
req.end()
}
/* eslint-disable quote-props */
function getGameName(searchStr, callback) {
const option = {
hostname: 'api.twitch.tv',
path: `/kraken/search/games?query=${searchStr}`,
method: 'GET',
headers: {
'Accept': 'application/vnd.twitchtv.v5+json',
'Client-ID': 'r0me6woz37936skc3tsuviuipkp9mb'
}
}
sendRequest(option, callback)
}
function getStreams(game, batchLimit, offset, callback) {
const option = {
hostname: 'api.twitch.tv',
path: `/kraken/streams/?game=${game}&limit=${batchLimit}&offset=${offset}`,
method: 'GET',
headers: {
'Accept': 'application/vnd.twitchtv.v5+json',
'Client-ID': 'r0me6woz37936skc3tsuviuipkp9mb'
}
}
sendRequest(option, callback)
}
function getMoreStreams(game, limit, total, callback) {
let streams = []
let offset = 0
function handleStreams(body) {
offset += limit
streams = streams.concat(body.streams)
if (streams.length < total && body.streams.length !== 0) {
getStreams(game, limit, offset, handleStreams)
} else {
callback(streams.slice(0, total))
}
}
getStreams(game, limit, offset, handleStreams)
}
// running
// callback 好難,偷看解答還是不太會寫:(
getGameName(process.argv[2], (body) => {
// e.g. 'League of Legends' -> 'League%20of%20Legends'
const game = encodeURIComponent(body.games[0].name)
getMoreStreams(game, BATCH_LIMIT, TOTAL, (body) => {
body.forEach((stream) => {
console.log(`status: ${stream.channel.status}, id: ${stream._id}`)
})
})
})