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

Commit

Permalink
refactor: switch to undici
Browse files Browse the repository at this point in the history
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
  • Loading branch information
ImRodry committed Apr 25, 2022
1 parent 776d77b commit 862a4e4
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 50 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,18 @@
"dependencies": {
"@crowdin/crowdin-api-client": "^1.17.0",
"@messageformat/core": "^3.0.1",
"axios": "^0.26.1",
"canvas": "2.9.0",
"discord.js": "14.0.0-dev.1650413390-585169f",
"language-flag-colors": "^2.0.4",
"mongodb": "^4.5.0",
"node-cron": "^3.0.0",
"puppeteer": "^13.6.0",
"typescript": "^4.6.3",
"undici": "^4.13.0",
"uuid": "^8.3.2"
},
"engines": {
"node": "16.x"
"node": "18.x"
},
"devDependencies": {
"@types/node": "^16.11.27",
Expand Down
2 changes: 1 addition & 1 deletion src/commands/Admin/eval.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable import/order */
/* eslint-disable @typescript-eslint/no-unused-vars */
const fs = require("node:fs"),
axios = require("axios"),
{ fetch } = require("undici"),
flagColors = require("language-flag-colors"),
{ colors, listeningStatuses, watchingStatuses, playingStatuses, ids } = require("../../config.json"),
{ crowdin } = require("../../index"),
Expand Down
19 changes: 9 additions & 10 deletions src/commands/Utility/hypixelstats.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import axios from "axios"
import { type GuildMember, type Message, EmbedBuilder, SelectMenuBuilder, ComponentType, ApplicationCommandOptionType, Colors } from "discord.js"
import { fetch } from "undici"

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 +48,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
11 changes: 5 additions & 6 deletions src/commands/Utility/hypixelverify.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import axios from "axios"
import { ApplicationCommandOptionType, EmbedBuilder } from "discord.js"
import { fetch } from "undici"

import { colors, ids } from "../../config.json"
import { db, type DbUser } from "../../lib/dbclient"
Expand Down Expand Up @@ -36,16 +36,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 @@ -41,7 +41,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
14 changes: 7 additions & 7 deletions src/commands/Utility/minecraft.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import axios from "axios"
import { ComponentType, GuildMember, Message, ApplicationCommandOptionType, EmbedBuilder } from "discord.js"
import { fetch } from "undici"

import { colors, ids } from "../../config.json"
import { client } from "../../index"
Expand Down Expand Up @@ -174,17 +174,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
33 changes: 21 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 All @@ -21,6 +20,7 @@ import {
LocaleString,
} from "discord.js"
import puppeteer from "puppeteer"
import { fetch, RequestInit } from "undici"
import { v4 } from "uuid"

import { db } from "./dbclient"
Expand All @@ -33,7 +33,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 +308,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 @@ -342,13 +345,14 @@ export function parseToNumberString(num: number, getString: GetStringFunction):
return format(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 @@ -620,4 +624,9 @@ export interface Stats {
errorMessage?: string
}

interface UUIDResponse {
name: string
id: string
}

// #endregion
20 changes: 9 additions & 11 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -406,13 +406,6 @@ axios@0.21.3:
dependencies:
follow-redirects "^1.14.0"

axios@^0.26.1:
version "0.26.1"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.26.1.tgz#1ede41c51fcf51bbbd6fd43669caaa4f0495aaa9"
integrity sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==
dependencies:
follow-redirects "^1.14.8"

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 @@ -1010,10 +1003,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.8:
version "1.14.9"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.9.tgz#dd4ea157de7bfaf9ea9b3fbd85aa16951f78d8d7"
integrity sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==
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==

form-data@^3.0.0:
version "3.0.1"
Expand Down Expand Up @@ -2155,6 +2148,11 @@ unbzip2-stream@1.4.3:
buffer "^5.2.1"
through "^2.3.8"

undici@^4.13.0:
version "4.13.0"
resolved "https://registry.yarnpkg.com/undici/-/undici-4.13.0.tgz#7d10fe150c3241a6b3b0eba80eff59c9fb40f359"
integrity sha512-8lk8S/f2V0VUNGf2scU2b+KI2JSzEQLdCyRNRF3XmHu+5jectlSDaPSBCXAHFaUlt1rzngzOBVDgJS9/Gue/KA==

undici@^4.16.0:
version "4.16.0"
resolved "https://registry.yarnpkg.com/undici/-/undici-4.16.0.tgz#469bb87b3b918818d3d7843d91a1d08da357d5ff"
Expand Down

0 comments on commit 862a4e4

Please sign in to comment.