InvestWeb/lib/7TVAPI.ts

127 lines
3.1 KiB
TypeScript
Raw Normal View History

2023-01-20 21:24:31 -05:00
import type RedisInstance from "ioredis";
2022-12-08 09:57:59 -05:00
async function applyCache(
2023-01-20 17:23:25 -05:00
redis: RedisInstance,
2022-12-08 09:57:59 -05:00
key: string,
query: string,
gql: boolean,
cacheTime: number
) {
if (await redis.get(key)) {
return JSON.parse((await redis.get(key)) as string);
} else {
2023-01-19 22:17:49 -05:00
const response = await fetchEndpoint(redis, query, gql);
2022-12-08 09:57:59 -05:00
if (response != null) {
await redis.set(key, JSON.stringify(response), "EX", cacheTime);
}
return response;
}
}
2023-01-19 22:17:49 -05:00
async function fetchEndpoint(
2023-01-20 17:23:25 -05:00
redis: RedisInstance,
2023-01-19 22:17:49 -05:00
query: string,
gql: boolean = false
) {
2022-12-08 09:57:59 -05:00
if (await redis.get("7TV.RATE_LIMIT")) {
await new Promise((resolve) => setTimeout(resolve, 1000));
} else {
await redis.set("7TV.RATE_LIMIT", "1", "EX", 1);
}
if (gql) {
const response = await fetchGQL(query);
const json = response.data;
return json;
} else {
const response = await fetch(query);
const json = await response.json();
return json;
}
}
async function fetchGQL(query: string) {
const response = await fetch("https://7tv.io/v3/gql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: query,
}),
});
const json = await response.json();
return json;
}
2023-01-20 17:23:25 -05:00
async function getGlobalEmotes(redis: RedisInstance) {
2022-12-08 09:57:59 -05:00
const gqlQuery = `query {
namedEmoteSet(name: GLOBAL) {
emote_count
emotes {
flags
id
name
data {
animated
flags
id
name
tags
host {
files {
format
height
width
name
size
}
url
}
}
}
}
}`;
2023-01-19 22:17:49 -05:00
return await applyCache(redis, "7TV.GLOBAL_EMOTES", gqlQuery, true, 3600);
2022-12-08 09:57:59 -05:00
}
2023-01-20 17:23:25 -05:00
async function getChannelEmotes(redis: RedisInstance, channelID: string) {
2022-12-08 09:57:59 -05:00
const gqlQuery = `query {
user(id: "${channelID}") {
emote_sets {
emote_count
emotes(origins: true) {
flags
id
name
data {
animated
flags
id
name
tags
host {
files {
format
height
width
name
size
}
url
}
}
}
}
}
}`;
return await applyCache(
2023-01-19 22:17:49 -05:00
redis,
2022-12-08 09:57:59 -05:00
"7TV.CHANNEL_EMOTES_" + channelID,
gqlQuery,
true,
1200
);
}
export { getGlobalEmotes, getChannelEmotes };