Skip to content
This repository has been archived by the owner on Nov 22, 2023. It is now read-only.

refactor: use global fetch #620

Merged
merged 1 commit into from
Jun 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"dependencies": {
"@crowdin/crowdin-api-client": "^1.18.2",
"@messageformat/core": "^3.0.1",
"axios": "^0.27.2",
"canvas": "^2.9.1",
"discord.js": "^14.0.0-dev.1655381041-4df491c",
"language-flag-colors": "^2.0.4",
Expand Down
1 change: 0 additions & 1 deletion src/commands/Admin/eval.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable import/order */
/* eslint-disable @typescript-eslint/no-unused-vars */
const fs = require("node:fs"),
axios = require("axios"),
flagColors = require("language-flag-colors"),
{ colors, listeningStatuses, watchingStatuses, playingStatuses, ids } = require("../../config.json"),
{ crowdin } = require("../../index"),
Expand Down
18 changes: 8 additions & 10 deletions src/commands/Utility/hypixelstats.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import axios from "axios"
import { type GuildMember, EmbedBuilder, SelectMenuBuilder, ComponentType, ApplicationCommandOptionType, Colors } from "discord.js"

import { ids } from "../../config.json"
import { client } from "../../index"
import { db, type DbUser } from "../../lib/dbclient"
import { fetchSettings, generateTip, getMCProfile, getUUID, gql, type GraphQLQuery, transformDiscordLocale, updateRoles } from "../../lib/util"
import { postSettings, generateTip, getMCProfile, getUUID, gql, type GraphQLQuery, transformDiscordLocale, updateRoles } from "../../lib/util"

import type { Command, GetStringFunction } from "../../lib/imports"

Expand Down Expand Up @@ -48,19 +47,18 @@ const command: Command = {
if (!uuid) throw "falseUser"

// Make a request to the slothpixel api (hypixel api but we dont need an api key)
const graphqlQuery = await axios
.get<GraphQLQuery>("https://api.slothpixel.me/api/graphql", {
...fetchSettings,
data: { query: query, variables: { uuid }, operationName: "HypixelStats" },
})
.then(res => res.data)
const graphqlQuery = (await fetch("https://api.slothpixel.me/api/graphql", {
...postSettings,
body: JSON.stringify({ query: query, variables: { uuid }, operationName: "HypixelStats" }),
})
.then(res => res.json())
.catch(e => {
if (e.code === "ECONNABORTED") {
if (e.code === "ECONNRESET") {
// This means the request timed out
console.error("Slothpixel is down, sending error.")
throw "apiError"
} else throw e
}),
})) as GraphQLQuery,
playerJson = graphqlQuery.data.players.player,
guildJson = graphqlQuery.data.guild

Expand Down
10 changes: 4 additions & 6 deletions src/commands/Utility/hypixelverify.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import axios from "axios"
import { ApplicationCommandOptionType, EmbedBuilder } from "discord.js"

import { colors, ids } from "../../config.json"
Expand Down Expand Up @@ -36,16 +35,15 @@ const command: Command = {
if (!uuid) throw "noUser"

// Make a response to the slothpixel api (hypixel api but we dont need an api key)
const json = await axios
.get<GraphQLQuery["data"]["players"]["player"] & { error?: string }>(`https://api.slothpixel.me/api/players/${uuid}`, fetchSettings)
.then(res => res.data)
const json = (await fetch(`https://api.slothpixel.me/api/players/${uuid}`, fetchSettings)
.then(res => res.json())
.catch(e => {
if (e.code === "ECONNABORTED") {
if (e.code === "ECONNRESET") {
// This means the request timed out
console.error("slothpixel is down, sending error.")
throw "apiError"
} else throw e
})
})) as GraphQLQuery["data"]["players"]["player"] & { error?: string }

// Handle errors
if (json.error === "Player does not exist" || json.error === "Invalid username or UUID!") throw "falseUser"
Expand Down
2 changes: 1 addition & 1 deletion src/commands/Utility/languagestats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const command: Command = {
.getProjectProgress(ids.projects.hypixel)
.then(res => res.data.find(language => language.data.languageId === lang.id)?.data ?? null)
.catch(e => {
if (e.code === "ECONNABORTED") {
if (e.code === "ECONNRESET") {
// This means the request timed out
console.error("Crowdin API is down, sending error.")
throw "apiError"
Expand Down
13 changes: 6 additions & 7 deletions src/commands/Utility/minecraft.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import axios from "axios"
import { ComponentType, GuildMember, ApplicationCommandOptionType, EmbedBuilder } from "discord.js"

import { colors, ids } from "../../config.json"
Expand Down Expand Up @@ -186,17 +185,17 @@ const command: Command = {
export default command

async function getPlayer(uuid: string) {
const json = await axios
.get<UserProfile & { error?: string }>(`https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`, fetchSettings)
.then(res => res.data)
const json = (await fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`, fetchSettings).then(res =>
res.json(),
)) as UserProfile & { error?: string }
if (json.error) throw "falseUUID"
return json
}

async function getNameHistory(uuid: string) {
const json = await axios
.get<NameHistory[] | MCAPIError>(`https://api.mojang.com/user/profiles/${uuid}/names`, fetchSettings)
.then(res => res.data || null)
const json = (await fetch(`https://api.mojang.com/user/profiles/${uuid}/names`, fetchSettings)
.then(res => res.json())
.catch(() => null)) as NameHistory[] | MCAPIError
if (!json || "error" in json) throw "falseUUID"
return json.reverse()
}
Expand Down
32 changes: 20 additions & 12 deletions src/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { readdirSync } from "node:fs"
import process from "node:process"
import { setInterval } from "node:timers"

import axios from "axios"
import {
type ChatInputCommandInteraction,
type GuildMember,
Expand Down Expand Up @@ -33,7 +32,12 @@ import type { ResponseObject, TranslationStatusModel } from "@crowdin/crowdin-ap

// #region Variables

export const fetchSettings = { headers: { "User-Agent": "Hypixel Translators Bot" }, timeout: 30_000 }
export const fetchSettings: RequestInit = { headers: { "User-Agent": "Hypixel Translators Bot" } }

export const postSettings: RequestInit = {
headers: { "Content-Type": "application/json", ...fetchSettings.headers },
method: "POST",
}

// Browser-related variables, not exported
let browser: puppeteer.Browser | null = null,
Expand Down Expand Up @@ -303,17 +307,15 @@ export async function getInviteLink() {
return `https://discord.gg/${inviteCode}`
}

export async function getMCProfile(uuid: string) {
return await axios
.get<MinecraftProfile>(`https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`, fetchSettings)
.then(json => json.data)
export function getMCProfile(uuid: string) {
return fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`, fetchSettings)
.then(res => res.json() as Promise<MinecraftProfile>)
.catch(() => null)
}

export async function getUUID(username: string): Promise<string | null> {
return await axios
.get(`https://api.mojang.com/users/profiles/minecraft/${username}`, fetchSettings)
.then(data => data.data.id ?? null)
export function getUUID(username: string) {
return fetch(`https://api.mojang.com/users/profiles/minecraft/${username}`, fetchSettings)
.then(async res => ((await res.json()) as UUIDResponse).id ?? null)
.catch(() => null)
}

Expand Down Expand Up @@ -350,13 +352,14 @@ export function parseToNumberString(num: number, getString: GetStringFunction):
return [format(num), num]
}

export async function restart(interaction?: ChatInputCommandInteraction) {
await axios.delete("https://api.heroku.com/apps/hypixel-translators/dynos", {
export function restart(interaction?: ChatInputCommandInteraction) {
return fetch("https://api.heroku.com/apps/hypixel-translators/dynos", {
headers: {
"User-Agent": `${interaction?.user.tag ?? client.user.tag}`,
Authorization: `Bearer ${process.env.HEROKU_API}`,
Accept: "application/vnd.heroku+json; version=3",
},
method: "DELETE",
})
}

Expand Down Expand Up @@ -628,4 +631,9 @@ export interface Stats {
errorMessage?: string
}

interface UUIDResponse {
name: string
id: string
}

// #endregion
54 changes: 4 additions & 50 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -379,26 +379,13 @@ array.prototype.flat@^1.2.5:
es-abstract "^1.19.2"
es-shim-unscopables "^1.0.0"

asynckit@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==

[email protected]:
version "0.21.3"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.21.3.tgz#f85d9b747f9b66d59ca463605cedf1844872b82e"
integrity sha512-JtoZ3Ndke/+Iwt5n+BgSli/3idTvpt5OjKyoCmz4LX5+lPiY5l7C1colYezhlxThjNa/NhngCUWZSZFypIFuaA==
dependencies:
follow-redirects "^1.14.0"

axios@^0.27.2:
version "0.27.2"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.27.2.tgz#207658cc8621606e586c85db4b41a750e756d972"
integrity sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==
dependencies:
follow-redirects "^1.14.9"
form-data "^4.0.0"

balanced-match@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
Expand Down Expand Up @@ -510,13 +497,6 @@ color-support@^1.1.2:
resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2"
integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==

combined-stream@^1.0.8:
version "1.0.8"
resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f"
integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
dependencies:
delayed-stream "~1.0.0"

[email protected]:
version "0.0.1"
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
Expand Down Expand Up @@ -584,11 +564,6 @@ define-properties@^1.1.3, define-properties@^1.1.4:
has-property-descriptors "^1.0.0"
object-keys "^1.1.1"

delayed-stream@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"
integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==

delegates@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a"
Expand Down Expand Up @@ -994,19 +969,10 @@ flatted@^3.1.0:
resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.5.tgz#76c8584f4fc843db64702a6bd04ab7a8bd666da3"
integrity sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==

follow-redirects@^1.14.0, follow-redirects@^1.14.9:
version "1.15.1"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.1.tgz#0ca6a452306c9b276e4d3127483e29575e207ad5"
integrity sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==

form-data@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452"
integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.8"
mime-types "^2.1.12"
follow-redirects@^1.14.0:
version "1.14.7"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.7.tgz#2004c02eb9436eee9a21446a6477debf17e81685"
integrity sha512-+hbxoLbFMbRKDwohX8GkTataGqO6Jb7jGwpAlwgy2bIz25XtRm7KEzJM76R1WiNT5SwZkX4Y75SwBolkpmE7iQ==

fs-constants@^1.0.0:
version "1.0.0"
Expand Down Expand Up @@ -1441,18 +1407,6 @@ micromatch@^4.0.4:
braces "^3.0.2"
picomatch "^2.3.1"

[email protected]:
version "1.52.0"
resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70"
integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==

mime-types@^2.1.12:
version "2.1.35"
resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a"
integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==
dependencies:
mime-db "1.52.0"

mimic-response@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-2.1.0.tgz#d13763d35f613d09ec37ebb30bac0469c0ee8f43"
Expand Down