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

Commit a348619

Browse files
committed
refactor: switch to undici
undici's fetch is coming to node in v18: nodejs/node#41749 Not putting this in production because undici is using many experimental node features for now Ref: 6ce33eb
1 parent 776d77b commit a348619

File tree

9 files changed

+56
-51
lines changed

9 files changed

+56
-51
lines changed

.github/workflows/lintCompile.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ jobs:
1515
- name: Use Node.js 16
1616
uses: actions/setup-node@v2
1717
with:
18-
node-version: 16
18+
node-version: 18
1919
cache: "yarn"
2020
- name: Install dependencies and compile
2121
run: yarn

package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,18 @@
1919
"dependencies": {
2020
"@crowdin/crowdin-api-client": "^1.17.0",
2121
"@messageformat/core": "^3.0.1",
22-
"axios": "^0.26.1",
2322
"canvas": "2.9.0",
2423
"discord.js": "14.0.0-dev.1650413390-585169f",
2524
"language-flag-colors": "^2.0.4",
2625
"mongodb": "^4.5.0",
2726
"node-cron": "^3.0.0",
2827
"puppeteer": "^13.6.0",
2928
"typescript": "^4.6.3",
29+
"undici": "^4.13.0",
3030
"uuid": "^8.3.2"
3131
},
3232
"engines": {
33-
"node": "16.x"
33+
"node": "18.x"
3434
},
3535
"devDependencies": {
3636
"@types/node": "^16.11.27",

src/commands/Admin/eval.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* eslint-disable import/order */
22
/* eslint-disable @typescript-eslint/no-unused-vars */
33
const fs = require("node:fs"),
4-
axios = require("axios"),
4+
{ fetch } = require("undici"),
55
flagColors = require("language-flag-colors"),
66
{ colors, listeningStatuses, watchingStatuses, playingStatuses, ids } = require("../../config.json"),
77
{ crowdin } = require("../../index"),

src/commands/Utility/hypixelstats.ts

+9-10
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import axios from "axios"
21
import { type GuildMember, type Message, EmbedBuilder, SelectMenuBuilder, ComponentType, ApplicationCommandOptionType, Colors } from "discord.js"
2+
import { fetch } from "undici"
33

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

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

@@ -48,19 +48,18 @@ const command: Command = {
4848
if (!uuid) throw "falseUser"
4949

5050
// Make a request to the slothpixel api (hypixel api but we dont need an api key)
51-
const graphqlQuery = await axios
52-
.get<GraphQLQuery>("https://api.slothpixel.me/api/graphql", {
53-
...fetchSettings,
54-
data: { query: query, variables: { uuid }, operationName: "HypixelStats" },
55-
})
56-
.then(res => res.data)
51+
const graphqlQuery = (await fetch("https://api.slothpixel.me/api/graphql", {
52+
...postSettings,
53+
body: JSON.stringify({ query: query, variables: { uuid }, operationName: "HypixelStats" }),
54+
})
55+
.then(res => res.json())
5756
.catch(e => {
58-
if (e.code === "ECONNABORTED") {
57+
if (e.code === "ECONNRESET") {
5958
// This means the request timed out
6059
console.error("Slothpixel is down, sending error.")
6160
throw "apiError"
6261
} else throw e
63-
}),
62+
})) as GraphQLQuery,
6463
playerJson = graphqlQuery.data.players.player,
6564
guildJson = graphqlQuery.data.guild
6665

src/commands/Utility/hypixelverify.ts

+5-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import axios from "axios"
21
import { ApplicationCommandOptionType, EmbedBuilder } from "discord.js"
2+
import { fetch } from "undici"
33

44
import { colors, ids } from "../../config.json"
55
import { db, type DbUser } from "../../lib/dbclient"
@@ -36,16 +36,15 @@ const command: Command = {
3636
if (!uuid) throw "noUser"
3737

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

5049
// Handle errors
5150
if (json.error === "Player does not exist" || json.error === "Invalid username or UUID!") throw "falseUser"

src/commands/Utility/languagestats.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ const command: Command = {
4141
.getProjectProgress(ids.projects.hypixel)
4242
.then(res => res.data.find(language => language.data.languageId === lang.id)?.data ?? null)
4343
.catch(e => {
44-
if (e.code === "ECONNABORTED") {
44+
if (e.code === "ECONNRESET") {
4545
// This means the request timed out
4646
console.error("Crowdin API is down, sending error.")
4747
throw "apiError"

src/commands/Utility/minecraft.ts

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import axios from "axios"
21
import { ComponentType, GuildMember, Message, ApplicationCommandOptionType, EmbedBuilder } from "discord.js"
2+
import { fetch } from "undici"
33

44
import { colors, ids } from "../../config.json"
55
import { client } from "../../index"
@@ -174,17 +174,17 @@ const command: Command = {
174174
export default command
175175

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

184184
async function getNameHistory(uuid: string) {
185-
const json = await axios
186-
.get<NameHistory[] | MCAPIError>(`https://api.mojang.com/user/profiles/${uuid}/names`, fetchSettings)
187-
.then(res => res.data || null)
185+
const json = (await fetch(`https://api.mojang.com/user/profiles/${uuid}/names`, fetchSettings)
186+
.then(res => res.json())
187+
.catch(() => null)) as NameHistory[] | MCAPIError
188188
if (!json || "error" in json) throw "falseUUID"
189189
return json.reverse()
190190
}

src/lib/util.ts

+21-12
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { readdirSync } from "node:fs"
33
import process from "node:process"
44
import { setInterval } from "node:timers"
55

6-
import axios from "axios"
76
import {
87
type ChatInputCommandInteraction,
98
type GuildMember,
@@ -21,6 +20,7 @@ import {
2120
LocaleString,
2221
} from "discord.js"
2322
import puppeteer from "puppeteer"
23+
import { fetch, RequestInit } from "undici"
2424
import { v4 } from "uuid"
2525

2626
import { db } from "./dbclient"
@@ -33,7 +33,12 @@ import type { ResponseObject, TranslationStatusModel } from "@crowdin/crowdin-ap
3333

3434
// #region Variables
3535

36-
export const fetchSettings = { headers: { "User-Agent": "Hypixel Translators Bot" }, timeout: 30_000 }
36+
export const fetchSettings: RequestInit = { headers: { "User-Agent": "Hypixel Translators Bot" } }
37+
38+
export const postSettings: RequestInit = {
39+
headers: { "Content-Type": "application/json", ...fetchSettings.headers },
40+
method: "POST",
41+
}
3742

3843
// Browser-related variables, not exported
3944
let browser: puppeteer.Browser | null = null,
@@ -303,17 +308,15 @@ export async function getInviteLink() {
303308
return `https://discord.gg/${inviteCode}`
304309
}
305310

306-
export async function getMCProfile(uuid: string) {
307-
return await axios
308-
.get<MinecraftProfile>(`https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`, fetchSettings)
309-
.then(json => json.data)
311+
export function getMCProfile(uuid: string) {
312+
return fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${uuid}`, fetchSettings)
313+
.then(res => res.json() as Promise<MinecraftProfile>)
310314
.catch(() => null)
311315
}
312316

313-
export async function getUUID(username: string): Promise<string | null> {
314-
return await axios
315-
.get(`https://api.mojang.com/users/profiles/minecraft/${username}`, fetchSettings)
316-
.then(data => data.data.id ?? null)
317+
export function getUUID(username: string) {
318+
return fetch(`https://api.mojang.com/users/profiles/minecraft/${username}`, fetchSettings)
319+
.then(async res => ((await res.json()) as UUIDResponse).id ?? null)
317320
.catch(() => null)
318321
}
319322

@@ -342,13 +345,14 @@ export function parseToNumberString(num: number, getString: GetStringFunction):
342345
return format(num)
343346
}
344347

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

@@ -620,4 +624,9 @@ export interface Stats {
620624
errorMessage?: string
621625
}
622626

627+
interface UUIDResponse {
628+
name: string
629+
id: string
630+
}
631+
623632
// #endregion

yarn.lock

+9-11
Original file line numberDiff line numberDiff line change
@@ -406,13 +406,6 @@ [email protected]:
406406
dependencies:
407407
follow-redirects "^1.14.0"
408408

409-
axios@^0.26.1:
410-
version "0.26.1"
411-
resolved "https://registry.yarnpkg.com/axios/-/axios-0.26.1.tgz#1ede41c51fcf51bbbd6fd43669caaa4f0495aaa9"
412-
integrity sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==
413-
dependencies:
414-
follow-redirects "^1.14.8"
415-
416409
balanced-match@^1.0.0:
417410
version "1.0.2"
418411
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
@@ -1010,10 +1003,10 @@ flatted@^3.1.0:
10101003
resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.5.tgz#76c8584f4fc843db64702a6bd04ab7a8bd666da3"
10111004
integrity sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==
10121005

1013-
follow-redirects@^1.14.0, follow-redirects@^1.14.8:
1014-
version "1.14.9"
1015-
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.9.tgz#dd4ea157de7bfaf9ea9b3fbd85aa16951f78d8d7"
1016-
integrity sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==
1006+
follow-redirects@^1.14.0:
1007+
version "1.14.7"
1008+
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.7.tgz#2004c02eb9436eee9a21446a6477debf17e81685"
1009+
integrity sha512-+hbxoLbFMbRKDwohX8GkTataGqO6Jb7jGwpAlwgy2bIz25XtRm7KEzJM76R1WiNT5SwZkX4Y75SwBolkpmE7iQ==
10171010

10181011
form-data@^3.0.0:
10191012
version "3.0.1"
@@ -2155,6 +2148,11 @@ [email protected]:
21552148
buffer "^5.2.1"
21562149
through "^2.3.8"
21572150

2151+
undici@^4.13.0:
2152+
version "4.13.0"
2153+
resolved "https://registry.yarnpkg.com/undici/-/undici-4.13.0.tgz#7d10fe150c3241a6b3b0eba80eff59c9fb40f359"
2154+
integrity sha512-8lk8S/f2V0VUNGf2scU2b+KI2JSzEQLdCyRNRF3XmHu+5jectlSDaPSBCXAHFaUlt1rzngzOBVDgJS9/Gue/KA==
2155+
21582156
undici@^4.16.0:
21592157
version "4.16.0"
21602158
resolved "https://registry.yarnpkg.com/undici/-/undici-4.16.0.tgz#469bb87b3b918818d3d7843d91a1d08da357d5ff"

0 commit comments

Comments
 (0)