Newer
Older

Yusuf Akgül
committed
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
import { IAuth, IGame } from "@/types/types"
import { getImageURL } from "./utils"
const AUTH_BASE_URL = process.env.TWITCH_AUTH_BASE_URL ?? ''
const IGDB_BASE_URL = process.env.IGDB_BASE_URL ?? ''
const CLIENT_ID = process.env.TWITCH_CLIENT_ID ?? ''
const CLIENT_SECRET = process.env.TWITCH_CLIENT_SECRET ?? ''
let _auth: IAuth
let _lastUpdate = 0
// fetches a new token if the current one is expired
async function getToken(): Promise<IAuth> {
if (!_auth || Date.now() - _lastUpdate > _auth.expires_in) {
const url = new URL(`${AUTH_BASE_URL}/token`)
url.searchParams.set('client_id', CLIENT_ID)
url.searchParams.set('client_secret', CLIENT_SECRET)
url.searchParams.set('grant_type', 'client_credentials')
const response = await fetch(url, { method: 'POST' })
_auth = await response.json() as IAuth
_lastUpdate = Date.now()
}
return _auth
}
// fetches the top 500 games with a rating of 96 or higher
export async function getGames(): Promise<IGame[]> {
const auth = await getToken()
const url = new URL(`${IGDB_BASE_URL}/games`)
const response = await fetch(url, {
method: 'POST',
headers: {
'Client-ID': CLIENT_ID,
'Authorization': `Bearer ${auth.access_token}`
},
body: `fields name, cover.*; limit 500; where rating > 96 & cover != null;`
})
const games = await response.json() as IGame[]
games.forEach(game => {
game.cover.url = getImageURL(game.cover.image_id, 'cover_big')
})
return games
}
// fetches a single game by id
export async function getGame(id: number): Promise<IGame[]> {
const auth = await getToken()
const url = new URL(`${IGDB_BASE_URL}/games`)
const response = await fetch(url, {
method: 'POST',
headers: {
'Client-ID': CLIENT_ID,
'Authorization': `Bearer ${auth.access_token}`
},
body: `fields name, cover.*, summary; where cover != null; where id = ${id};`
})
const games = await response.json() as IGame[]
games.forEach(game => {
game.cover.url = getImageURL(game.cover.image_id, 'cover_big')
})
return games
}