forked from dajk/hltv-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matches.ts
98 lines (80 loc) · 2.33 KB
/
matches.ts
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
88
89
90
91
92
93
94
95
96
97
98
import cheerio from 'cheerio'
import fetch from 'node-fetch'
import { CONFIG, MAPS } from './config'
interface IEvent {
name: string
logo: string
}
interface ITeam {
name: string
logo: string
}
interface IMatch {
id: number
time: string
event: IEvent
stars: number
maps: string
teams: ITeam[]
}
export async function getMatches() {
const url = `${CONFIG.BASE}/${CONFIG.MATCHES}`
try {
const body = await (
await fetch(url, {
headers: { 'User-Agent': 'node-fetch' },
})
).text()
const $ = cheerio.load(body, {
normalizeWhitespace: true,
})
const allContent = $('.upcomingMatch')
const matches: IMatch[] = []
allContent.map((_i, element) => {
const el = $(element)
const link = el.children('a').attr('href') as string
const id = Number(link.split('/')[2])
const time = new Date(parseInt(el.find('.matchTime').attr('data-unix')!, 10)).toISOString()
const event: IEvent = {
name: el.find('.matchEventName').text(),
logo: el.find('.matchEventLogo').attr('src') as string,
}
const stars = Number(el.attr('stars'))
const map: keyof typeof MAPS = el.find('.matchMeta').text() as any
const teamsEl = el.find('.matchTeams')
// return just valid matches
if (!teamsEl.html()) {
return
}
const team1El = teamsEl.find('.matchTeam.team1')
const team2El = teamsEl.find('.matchTeam.team2')
const team1 = {
id: Number(el.attr('team1')),
name: team1El.find('.matchTeamName').text() || /* istanbul ignore next */ 'n/a',
logo: team1El.find('.matchTeamLogo').attr('src') as string,
}
const team2 = {
id: Number(el.attr('team2')),
name: team2El.find('.matchTeamName').text() || 'n/a',
logo: team2El.find('.matchTeamLogo').attr('src') as string,
}
const response: IMatch = {
id,
time,
event,
stars,
maps: MAPS[map] || map,
teams: [team1, team2],
}
matches[matches.length] = response
})
if (!matches.length) {
throw new Error(
'There are no matches available, something went wrong. Please contact the library maintainer on https://github.com/dajk/hltv-api'
)
}
return matches
} catch (error) {
throw new Error(error as any)
}
}