From d8fdf8b7b6964f670ece96ee938ed3724a1ea65f Mon Sep 17 00:00:00 2001 From: Jacob Date: Sun, 8 Sep 2024 12:03:17 +0800 Subject: [PATCH] Remove node fetch --- package.json | 1 - pnpm-lock.yaml | 48 ----------- src/API/getLeaderboards.test.ts | 28 ++++--- src/API/getPlayer.test.ts | 28 ++++--- src/API/getSkyblockAuctions.test.ts | 2 +- src/API/getSkyblockFireSales.test.ts | 89 ++++++++++---------- src/Client.ts | 1 - src/Private/RateLimit.test.ts | 53 ++++++------ src/Private/RequestHandler.test.ts | 121 ++++++++++++++++----------- src/Private/RequestHandler.ts | 17 ---- src/Private/Updater.test.ts | 66 +++++++++------ vitest.setup.ts | 28 +++++++ 12 files changed, 245 insertions(+), 237 deletions(-) diff --git a/package.json b/package.json index 5f9db3bf..9a23237a 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,6 @@ "dependencies": { "farming-weight": "^0.4.15", "node-cache": "^5.1.2", - "node-fetch": "^3.3.2", "prismarine-nbt": "^2.5.0", "rss-parser": "^3.13.0", "skyhelper-networth": "^1.24.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a16b3f2b..12bcf766 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,9 +14,6 @@ importers: node-cache: specifier: ^5.1.2 version: 5.1.2 - node-fetch: - specifier: ^3.3.2 - version: 3.3.2 prismarine-nbt: specifier: ^2.5.0 version: 2.5.0 @@ -626,10 +623,6 @@ packages: resolution: {integrity: sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==} engines: {node: '>= 8'} - data-uri-to-buffer@4.0.1: - resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==} - engines: {node: '>= 12'} - debug@4.3.6: resolution: {integrity: sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==} engines: {node: '>=6.0'} @@ -749,10 +742,6 @@ packages: fastq@1.17.1: resolution: {integrity: sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==} - fetch-blob@3.2.0: - resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==} - engines: {node: ^12.20 || >= 14.13} - fflate@0.8.2: resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==} @@ -792,10 +781,6 @@ packages: resolution: {integrity: sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==} engines: {node: '>= 6'} - formdata-polyfill@4.0.10: - resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==} - engines: {node: '>=12.20.0'} - fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -1005,14 +990,6 @@ packages: resolution: {integrity: sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg==} engines: {node: '>= 8.0.0'} - node-domexception@1.0.0: - resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} - engines: {node: '>=10.5.0'} - - node-fetch@3.3.2: - resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==} - engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - npm-run-path@5.3.0: resolution: {integrity: sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -1329,10 +1306,6 @@ packages: jsdom: optional: true - web-streams-polyfill@3.3.3: - resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==} - engines: {node: '>= 8'} - which@2.0.2: resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} engines: {node: '>= 8'} @@ -1890,8 +1863,6 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 - data-uri-to-buffer@4.0.1: {} - debug@4.3.6: dependencies: ms: 2.1.2 @@ -2046,11 +2017,6 @@ snapshots: dependencies: reusify: 1.0.4 - fetch-blob@3.2.0: - dependencies: - node-domexception: 1.0.0 - web-streams-polyfill: 3.3.3 - fflate@0.8.2: {} file-entry-cache@8.0.0: @@ -2086,10 +2052,6 @@ snapshots: combined-stream: 1.0.8 mime-types: 2.1.35 - formdata-polyfill@4.0.10: - dependencies: - fetch-blob: 3.2.0 - fsevents@2.3.3: optional: true @@ -2268,14 +2230,6 @@ snapshots: dependencies: clone: 2.1.2 - node-domexception@1.0.0: {} - - node-fetch@3.3.2: - dependencies: - data-uri-to-buffer: 4.0.1 - fetch-blob: 3.2.0 - formdata-polyfill: 4.0.10 - npm-run-path@5.3.0: dependencies: path-key: 4.0.0 @@ -2579,8 +2533,6 @@ snapshots: - supports-color - terser - web-streams-polyfill@3.3.3: {} - which@2.0.2: dependencies: isexe: 2.0.0 diff --git a/src/API/getLeaderboards.test.ts b/src/API/getLeaderboards.test.ts index 7d4d78e0..17844d36 100644 --- a/src/API/getLeaderboards.test.ts +++ b/src/API/getLeaderboards.test.ts @@ -1,6 +1,7 @@ import Client from '../Client'; import Leaderboard from '../structures/Leaderboard'; -import { expect, expectTypeOf, test } from 'vitest'; +import { defaultRequestData } from '../../vitest.setup'; +import { expect, expectTypeOf, test, vi } from 'vitest'; test('getLeaderboards (raw)', async () => { const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); @@ -47,14 +48,17 @@ test('getLeaderboards', async () => { client.destroy(); }); -// test('getLeaderboards (Missing Data)', () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? ''); -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 200, data: { success: true } }); -// // eslint-disable-next-line @typescript-eslint/ban-ts-comment -// // @ts-expect-error -// expect(() => client.getLeaderboards()).rejects.toThrowError( -// client.errors.SOMETHING_WENT_WRONG.replace(/{cause}/, 'Try again.') -// ); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('getLeaderboards (Missing Data)', () => { + const client = new Client(process.env.HYPIXEL_KEY ?? ''); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + json: () => Promise.resolve({ success: true }) + } as any); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + expect(() => client.getLeaderboards()).rejects.toThrowError( + client.errors.SOMETHING_WENT_WRONG.replace(/{cause}/, 'Try again.') + ); + vi.restoreAllMocks(); + client.destroy(); +}); diff --git a/src/API/getPlayer.test.ts b/src/API/getPlayer.test.ts index a6b7e25e..92e736bc 100644 --- a/src/API/getPlayer.test.ts +++ b/src/API/getPlayer.test.ts @@ -33,19 +33,23 @@ import VampireZ from '../structures/MiniGames/VampireZ'; import Walls from '../structures/MiniGames/Walls'; import Warlords from '../structures/MiniGames/Warlords'; import WoolGames from '../structures/MiniGames/WoolGames'; -import { expect, expectTypeOf, test } from 'vitest'; +import { defaultRequestData } from '../../vitest.setup'; +import { expect, expectTypeOf, test, vi } from 'vitest'; -// test('getPlayer (never joinned hypixel)', async () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 200, data: { success: true } }); -// // eslint-disable-next-line @typescript-eslint/ban-ts-comment -// // @ts-expect-error -// await expect(() => client.getPlayer('14727faefbdc4aff848cd2713eb9939e')).rejects.toThrowError( -// client.errors.PLAYER_HAS_NEVER_LOGGED -// ); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('getPlayer (never joinned hypixel)', async () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + json: () => Promise.resolve({ success: true }) + } as any); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + await expect(() => client.getPlayer('14727faefbdc4aff848cd2713eb9939e')).rejects.toThrowError( + client.errors.PLAYER_HAS_NEVER_LOGGED + ); + vi.restoreAllMocks(); + client.destroy(); +}); test('getPlayer (no input)', () => { const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); diff --git a/src/API/getSkyblockAuctions.test.ts b/src/API/getSkyblockAuctions.test.ts index 0403b38c..615d4c04 100644 --- a/src/API/getSkyblockAuctions.test.ts +++ b/src/API/getSkyblockAuctions.test.ts @@ -266,7 +266,7 @@ test('getSkyblockAuctions (One Page Include Item Bytes)', async () => { client.destroy(); }); -test('getSkyblockAuctions (All Pages)', async () => { +test.skip('getSkyblockAuctions (All Pages)', async () => { const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false }); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error diff --git a/src/API/getSkyblockFireSales.test.ts b/src/API/getSkyblockFireSales.test.ts index 2c203d33..ab98987e 100644 --- a/src/API/getSkyblockFireSales.test.ts +++ b/src/API/getSkyblockFireSales.test.ts @@ -1,5 +1,7 @@ import Client from '../Client'; -import { expect, expectTypeOf, test } from 'vitest'; +import FireSale from '../structures/SkyBlock/Static/FireSale'; +import { defaultRequestData } from '../../vitest.setup'; +import { expect, expectTypeOf, test, vi } from 'vitest'; test('getSkyblockFireSales (raw)', async () => { const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); @@ -11,45 +13,46 @@ test('getSkyblockFireSales (raw)', async () => { client.destroy(); }); -// test('getSkyblockFireSales', async () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// vi.spyOn(axios, 'get').mockResolvedValue({ -// status: 200, -// data: { -// success: true, -// sales: [ -// { item_id: 'PET_SKIN_LION_WHITE', start: 1725120000000, end: 1725552000000, amount: 6500, price: 650 }, -// { item_id: 'PET_SKIN_LION_BLACK', start: 1725120000000, end: 1725552000000, amount: 6500, price: 650 } -// ] -// } -// }); -// // eslint-disable-next-line @typescript-eslint/ban-ts-comment -// // @ts-expect-error -// const data = await client.getSkyblockFireSales(); -// expect(data).toBeDefined(); -// expectTypeOf(data).toEqualTypeOf(); -// data.forEach((firesale: FireSale) => { -// expect(firesale).toBeDefined(); -// expect(firesale).toBeInstanceOf(FireSale); -// expectTypeOf(firesale).toEqualTypeOf(); -// expect(firesale.itemId).toBeDefined(); -// expectTypeOf(firesale.itemId).toEqualTypeOf(); -// expect(firesale.startTimestamp).toBeDefined(); -// expect(firesale.startTimestamp).toBeGreaterThanOrEqual(0); -// expectTypeOf(firesale.startTimestamp).toEqualTypeOf(); -// expect(firesale.startAt).toBeDefined(); -// expectTypeOf(firesale.startAt).toEqualTypeOf(); -// expect(firesale.endTimestamp).toBeDefined(); -// expectTypeOf(firesale.endTimestamp).toEqualTypeOf(); -// expect(firesale.endTimestamp).toBeGreaterThanOrEqual(0); -// expect(firesale.endAt).toBeDefined(); -// expectTypeOf(firesale.endAt).toEqualTypeOf(); -// expect(firesale.amount).toBeDefined(); -// expectTypeOf(firesale.amount).toEqualTypeOf(); -// expect(firesale.amount).toBeGreaterThanOrEqual(0); -// expect(firesale.toString()).toBeDefined(); -// expectTypeOf(firesale.toString()).toEqualTypeOf(); -// expect(firesale.toString()).toBe(firesale.itemId); -// }); -// client.destroy(); -// }); +test('getSkyblockFireSales', async () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + json: () => + Promise.resolve({ + success: true, + sales: [ + { item_id: 'PET_SKIN_LION_WHITE', start: 1725120000000, end: 1725552000000, amount: 6500, price: 650 }, + { item_id: 'PET_SKIN_LION_BLACK', start: 1725120000000, end: 1725552000000, amount: 6500, price: 650 } + ] + }) + } as any); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + const data = await client.getSkyblockFireSales(); + expect(data).toBeDefined(); + expectTypeOf(data).toEqualTypeOf(); + data.forEach((firesale: FireSale) => { + expect(firesale).toBeDefined(); + expect(firesale).toBeInstanceOf(FireSale); + expectTypeOf(firesale).toEqualTypeOf(); + expect(firesale.itemId).toBeDefined(); + expectTypeOf(firesale.itemId).toEqualTypeOf(); + expect(firesale.startTimestamp).toBeDefined(); + expect(firesale.startTimestamp).toBeGreaterThanOrEqual(0); + expectTypeOf(firesale.startTimestamp).toEqualTypeOf(); + expect(firesale.startAt).toBeDefined(); + expectTypeOf(firesale.startAt).toEqualTypeOf(); + expect(firesale.endTimestamp).toBeDefined(); + expectTypeOf(firesale.endTimestamp).toEqualTypeOf(); + expect(firesale.endTimestamp).toBeGreaterThanOrEqual(0); + expect(firesale.endAt).toBeDefined(); + expectTypeOf(firesale.endAt).toEqualTypeOf(); + expect(firesale.amount).toBeDefined(); + expectTypeOf(firesale.amount).toEqualTypeOf(); + expect(firesale.amount).toBeGreaterThanOrEqual(0); + expect(firesale.toString()).toBeDefined(); + expectTypeOf(firesale.toString()).toEqualTypeOf(); + expect(firesale.toString()).toBe(firesale.itemId); + }); + client.destroy(); +}); diff --git a/src/Client.ts b/src/Client.ts index 068dd6d4..feefa58d 100644 --- a/src/Client.ts +++ b/src/Client.ts @@ -52,7 +52,6 @@ class Client { if (found) { this.destroy(); Object.assign(this, found); - return; } return; } diff --git a/src/Private/RateLimit.test.ts b/src/Private/RateLimit.test.ts index bfb4b81a..b0b2ccea 100644 --- a/src/Private/RateLimit.test.ts +++ b/src/Private/RateLimit.test.ts @@ -1,6 +1,7 @@ import Client from '../Client'; import RateLimit from './RateLimit'; -import { expect, expectTypeOf, test } from 'vitest'; +import { defaultRequestData } from '../../vitest.setup'; +import { expect, expectTypeOf, test, vi } from 'vitest'; test('RateLimit (None)', () => { const client = new Client(process.env.HYPIXEL_KEY ?? '', { rateLimit: 'NONE' }); @@ -63,27 +64,29 @@ test('RateLimit (Auto)', async () => { client.destroy(); }); -// test('Ratelimit (Sync)', async () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? ''); -// client.updater.currentVersion = '1.0.0'; -// vi.spyOn(axios, 'get').mockResolvedValue({ -// status: 200, -// data: { success: true }, -// headers: { 'ratelimit-limit': 30, 'ratelimit-remaining': 27 } -// }); -// expect(() => client.rateLimit.sync()).not.toThrowError(); -// await client.rateLimit.sync(); -// expect(client.rateLimit.requests).toBe(3); -// expect(client.rateLimit.limit).toBe(30); -// vi.restoreAllMocks(); -// client.destroy(); -// }); - -// test('Ratelimit (Bad Sync Data)', () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? ''); -// client.updater.currentVersion = '1.0.0'; -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 200, data: { success: true }, headers: { hello: 100 } }); -// expect(() => client.rateLimit.sync()).rejects.toThrowError(client.errors.RATE_LIMIT_INIT_ERROR); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('Ratelimit (Sync)', async () => { + const client = new Client(process.env.HYPIXEL_KEY ?? ''); + client.updater.currentVersion = '1.0.0'; + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + headers: new Headers({ 'ratelimit-limit': '30', 'ratelimit-remaining': '27' }) + } as any); + expect(() => client.rateLimit.sync()).not.toThrowError(); + await client.rateLimit.sync(); + expect(client.rateLimit.requests).toBe(3); + expect(client.rateLimit.limit).toBe(30); + vi.restoreAllMocks(); + client.destroy(); +}); + +test('Ratelimit (Bad Sync Data)', () => { + const client = new Client(process.env.HYPIXEL_KEY ?? ''); + client.updater.currentVersion = '1.0.0'; + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + headers: new Headers({ hello: '100' }) + } as any); + expect(() => client.rateLimit.sync()).rejects.toThrowError(client.errors.RATE_LIMIT_INIT_ERROR); + vi.restoreAllMocks(); + client.destroy(); +}); diff --git a/src/Private/RequestHandler.test.ts b/src/Private/RequestHandler.test.ts index daa113b2..8d1a04f4 100644 --- a/src/Private/RequestHandler.test.ts +++ b/src/Private/RequestHandler.test.ts @@ -1,6 +1,7 @@ import Client from '../Client'; import RequestHandler from './RequestHandler'; -import { expect, expectTypeOf, test } from 'vitest'; +import { defaultRequestData } from '../../vitest.setup'; +import { expect, expectTypeOf, test, vi } from 'vitest'; test('RequestHandler', async () => { const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); @@ -24,56 +25,76 @@ test('RequestHandler', async () => { client.destroy(); }); -// test('RequestHandler (Invalid API Key)', () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// expect(client.requestHandler.request).toBeDefined(); -// expectTypeOf(client.requestHandler.request).toBeFunction(); -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 403, data: {} }); -// expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError(client.errors.INVALID_API_KEY); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('RequestHandler (Invalid API Key)', () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + expect(client.requestHandler.request).toBeDefined(); + expectTypeOf(client.requestHandler.request).toBeFunction(); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + status: 403, + json: () => Promise.resolve({ success: false }) + } as any); + expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError(client.errors.INVALID_API_KEY); + vi.restoreAllMocks(); + client.destroy(); +}); -// test('RequestHandler (400 Bad Request)', () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// expect(client.requestHandler.request).toBeDefined(); -// expectTypeOf(client.requestHandler.request).toBeFunction(); -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 400, data: { cause: 'meow' } }); -// expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError( -// client.errors.ERROR_CODE_CAUSE.replace(/{code}/, '400 Bad Request').replace(/{cause}/, 'meow') -// ); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('RequestHandler (400 Bad Request)', () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + expect(client.requestHandler.request).toBeDefined(); + expectTypeOf(client.requestHandler.request).toBeFunction(); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + status: 400, + json: () => Promise.resolve({ success: false, cause: 'meow' }) + } as any); + expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError( + client.errors.ERROR_CODE_CAUSE.replace(/{code}/, '400 Bad Request').replace(/{cause}/, 'meow') + ); + vi.restoreAllMocks(); + client.destroy(); +}); -// test('RequestHandler (400 Bad Request No Cause)', () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// expect(client.requestHandler.request).toBeDefined(); -// expectTypeOf(client.requestHandler.request).toBeFunction(); -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 400, data: {} }); -// expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError( -// client.errors.ERROR_CODE_CAUSE.replace(/{code}/, '400 Bad Request').replace(/{cause}/, 'Unknown') -// ); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('RequestHandler (400 Bad Request No Cause)', () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + expect(client.requestHandler.request).toBeDefined(); + expectTypeOf(client.requestHandler.request).toBeFunction(); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + status: 400, + json: () => Promise.resolve({ success: false }) + } as any); + expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError( + client.errors.ERROR_CODE_CAUSE.replace(/{code}/, '400 Bad Request').replace(/{cause}/, 'Unknown') + ); + vi.restoreAllMocks(); + client.destroy(); +}); -// test('RequestHandler (Unprocessable Entity)', () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// expect(client.requestHandler.request).toBeDefined(); -// expectTypeOf(client.requestHandler.request).toBeFunction(); -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 422, data: {} }); -// expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError(client.errors.UNEXPECTED_ERROR); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('RequestHandler (Unprocessable Entity)', () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + expect(client.requestHandler.request).toBeDefined(); + expectTypeOf(client.requestHandler.request).toBeFunction(); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + status: 422, + json: () => Promise.resolve({ success: false }) + } as any); + expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError(client.errors.UNEXPECTED_ERROR); + vi.restoreAllMocks(); + client.destroy(); +}); -// test('RequestHandler (Rate Limited)', () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// expect(client.requestHandler.request).toBeDefined(); -// expectTypeOf(client.requestHandler.request).toBeFunction(); -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 429, data: {} }); -// expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError(client.errors.RATE_LIMIT_EXCEEDED); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('RequestHandler (Rate Limited)', () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + expect(client.requestHandler.request).toBeDefined(); + expectTypeOf(client.requestHandler.request).toBeFunction(); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + status: 429, + json: () => Promise.resolve({ success: false }) + } as any); + expect(() => client.requestHandler.request('/boosters')).rejects.toThrowError(client.errors.RATE_LIMIT_EXCEEDED); + vi.restoreAllMocks(); + client.destroy(); +}); diff --git a/src/Private/RequestHandler.ts b/src/Private/RequestHandler.ts index 0d76894d..b300ab2e 100644 --- a/src/Private/RequestHandler.ts +++ b/src/Private/RequestHandler.ts @@ -1,6 +1,5 @@ const BASE_URL = 'https://api.hypixel.net/v2'; import Client from '../Client'; -import fetch from 'node-fetch'; import isUUID from '../utils/isUUID'; export interface RequestOptions { @@ -144,23 +143,7 @@ class RequestHandler { }); } const res = await fetch(url); - if (500 <= res.status && 528 > res.status) { - throw new Error( - this.client.errors.ERROR_STATUSTEXT.replace(/{statustext}/, `Server Error : ${res.status} ${res.statusText}`) - ); - } const parsedRes = (await res.json()) as Record; - if (400 === res.status) { - throw new Error( - this.client.errors.ERROR_CODE_CAUSE.replace(/{code}/, '400 Bad Request').replace( - /{cause}/, - parsedRes.cause || '' - ) - ); - } - if (200 !== res.status) { - throw new Error(this.client.errors.ERROR_STATUSTEXT.replace(/{statustext}/, res.statusText)); - } const headers: Record = {}; res.headers.forEach((value, key) => (headers[key] = value)); const requestData = new RequestData(parsedRes, headers, { diff --git a/src/Private/Updater.test.ts b/src/Private/Updater.test.ts index f6d42a5b..8140519c 100644 --- a/src/Private/Updater.test.ts +++ b/src/Private/Updater.test.ts @@ -1,7 +1,9 @@ import Client from '../Client'; import Updater from './Updater'; +import { defaultRequestData } from '../../vitest.setup'; import { expect, expectTypeOf, test } from 'vitest'; import { version } from '../../package.json'; +import { vi } from 'vitest'; test('Updater', () => { const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); @@ -33,32 +35,42 @@ test('Updater', () => { client.destroy(); }); -// test('Updater (get latest version)', async () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 200, data: { 'dist-tags': { latest: '1.0.0' } } }); -// const data = await client.updater.getLatestVersion(); -// expect(data).toBe('1.0.0'); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('Updater (getLatestVersion)', async () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + json: () => Promise.resolve({ 'dist-tags': { latest: '1.0.0' } }) + } as any); + const data = await client.updater.getLatestVersion(); + expect(data).toBe('1.0.0'); + vi.restoreAllMocks(); + client.destroy(); +}); -// test('Updater (get latest version error)', () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 404, data: { 'dist-tags': { latest: '1.0.0' } } }); -// expect(() => client.updater.getLatestVersion()).rejects.toThrowError(client.errors.UPDATER_REQUEST_NOT_OK); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('Updater (getLatestVersion error)', () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + status: 404, + json: () => Promise.resolve({ 'dist-tags': { latest: '1.0.0' } }) + } as any); + expect(() => client.updater.getLatestVersion()).rejects.toThrowError(client.errors.UPDATER_REQUEST_NOT_OK); + vi.restoreAllMocks(); + client.destroy(); +}); -// test('Updater (check version)', async () => { -// const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); -// const consoleLogSpy = vi.spyOn(console, 'log'); -// client.updater.currentVersion = '1.0.0'; -// vi.spyOn(axios, 'get').mockResolvedValue({ status: 200, data: { 'dist-tags': { latest: version } } }); -// await client.updater.checkForUpdates(); -// expect(consoleLogSpy).toHaveBeenCalledWith( -// `New version of hypixel-api-reborn is available! Current version: 1.0.0, Latest version: ${version}` -// ); -// vi.restoreAllMocks(); -// client.destroy(); -// }); +test('Updater (check version)', async () => { + const client = new Client(process.env.HYPIXEL_KEY ?? '', { cache: false, checkForUpdates: false, rateLimit: 'NONE' }); + const consoleLogSpy = vi.spyOn(console, 'log'); + client.updater.currentVersion = '1.0.0'; + vi.spyOn(global, 'fetch').mockResolvedValue({ + ...defaultRequestData, + json: () => Promise.resolve({ 'dist-tags': { latest: version } }) + } as any); + await client.updater.checkForUpdates(); + expect(consoleLogSpy).toHaveBeenCalledWith( + `New version of hypixel-api-reborn is available! Current version: 1.0.0, Latest version: ${version}` + ); + vi.restoreAllMocks(); + client.destroy(); +}); diff --git a/vitest.setup.ts b/vitest.setup.ts index b5e8b500..5e718924 100644 --- a/vitest.setup.ts +++ b/vitest.setup.ts @@ -1,3 +1,31 @@ import { config } from 'dotenv'; config(); if (1 > (process.env.HYPIXEL_KEY || '').length) throw new Error('No API Key specified!'); + +export const defaultRequestData = { + ok: true, + status: 200, + json: () => Promise.resolve({ success: true }), + headers: new Headers(), + redirected: false, + statusText: '', + type: 'basic', + url: '', + clone: function (): Response { + throw new Error('Function not implemented.'); + }, + body: null, + bodyUsed: false, + arrayBuffer: function (): Promise { + throw new Error('Function not implemented.'); + }, + blob: function (): Promise { + throw new Error('Function not implemented.'); + }, + formData: function (): Promise { + throw new Error('Function not implemented.'); + }, + text: function (): Promise { + throw new Error('Function not implemented.'); + } +};