Add GetStatsOptions for getStats

This commit is contained in:
maxswa
2023-03-19 23:14:10 -04:00
parent dc799cf363
commit 54c11635e0
3 changed files with 106 additions and 38 deletions

View File

@@ -505,3 +505,50 @@ test('Get stats by gamemode', async () => {
expect.assertions(2); expect.assertions(2);
}); });
describe('Get stats options', () => {
const rsn = 'player';
let axiosMock: jest.Mock;
beforeEach(() => {
axios.get = jest.fn(
(url) =>
new Promise<any>((resolve) =>
resolve(
url === getPlayerTableURL('main', rsn)
? { data: lynxTitanNamePage }
: { status: 200, data: lynxTitanStats }
)
)
);
axiosMock = axios.get as any;
axiosMock.mockClear();
});
it('fetches all gamemodes and formatted RSN when no options provided', async () => {
await getStats(rsn);
expect(axiosMock.mock.calls.map((val) => val[0])).toEqual([
getStatsURL('main', rsn),
getPlayerTableURL('main', rsn),
getStatsURL('ironman', rsn),
getStatsURL('hardcore', rsn),
getStatsURL('ultimate', rsn)
]);
});
it('skips fetching formatted RSN when option is provided', async () => {
await getStats(rsn, { shouldGetFormattedRsn: false });
expect(
axiosMock.mock.calls.some(
(val) => val[0] === getPlayerTableURL('main', rsn)
)
).toBeFalsy();
});
it('skips fetching game mode when option is provided', async () => {
await getStats(rsn, {
otherGamemodes: ['ironman', 'ultimate']
});
expect(
axiosMock.mock.calls.some(
(val) => val[0] === getStatsURL('hardcore', rsn)
)
).toBeFalsy();
});
});

View File

@@ -1,4 +1,5 @@
import { JSDOM } from 'jsdom'; import { AxiosResponse } from 'axios';
import { BinaryData, JSDOM } from 'jsdom';
import { import {
Player, Player,
Activity, Activity,
@@ -12,7 +13,8 @@ import {
PlayerSkillRow, PlayerSkillRow,
ActivityName, ActivityName,
PlayerActivityRow, PlayerActivityRow,
Bosses Bosses,
GetStatsOptions
} from './types'; } from './types';
import { import {
getStatsURL, getStatsURL,
@@ -28,7 +30,8 @@ import {
getActivityPageURL, getActivityPageURL,
httpGet, httpGet,
BOSSES, BOSSES,
INVALID_FORMAT_ERROR INVALID_FORMAT_ERROR,
validateRSN
} from './utils'; } from './utils';
/** /**
@@ -38,17 +41,13 @@ import {
* @returns Formatted version of the rsn. * @returns Formatted version of the rsn.
*/ */
export async function getRSNFormat(rsn: string): Promise<string> { export async function getRSNFormat(rsn: string): Promise<string> {
if (typeof rsn !== 'string') { validateRSN(rsn);
throw Error('RSN must be a string');
} else if (!/^[a-zA-Z0-9 _-]+$/.test(rsn)) {
throw Error('RSN contains invalid character');
} else if (rsn.length > 12 || rsn.length < 1) {
throw Error('RSN must be between 1 and 12 characters');
}
const url = getPlayerTableURL('main', rsn); const url = getPlayerTableURL('main', rsn);
try { try {
const response = await httpGet(url); const response = await httpGet<string | Buffer | BinaryData | undefined>(
url
);
const dom = new JSDOM(response.data); const dom = new JSDOM(response.data);
const anchor = dom.window.document.querySelector( const anchor = dom.window.document.querySelector(
'.personal-hiscores__row.personal-hiscores__row--type-highlight a' '.personal-hiscores__row.personal-hiscores__row--type-highlight a'
@@ -163,25 +162,36 @@ export function parseStats(csv: string): Stats {
* @param rsn Username of the player. * @param rsn Username of the player.
* @returns Player object. * @returns Player object.
*/ */
export async function getStats(rsn: string): Promise<Player> { export async function getStats(
if (typeof rsn !== 'string') { rsn: string,
throw Error('RSN must be a string'); options?: GetStatsOptions
} else if (!/^[a-zA-Z0-9 _-]+$/.test(rsn)) { ): Promise<Player> {
throw Error('RSN contains invalid character'); validateRSN(rsn);
} else if (rsn.length > 12 || rsn.length < 1) { const otherGamemodes = options?.otherGamemodes ?? [
throw Error('RSN must be between 1 and 12 characters'); 'ironman',
} 'hardcore',
'ultimate'
];
const shouldGetFormattedRsn = options?.shouldGetFormattedRsn ?? true;
const mainRes = await httpGet(getStatsURL('main', rsn)); const mainRes = await httpGet<string>(getStatsURL('main', rsn));
if (mainRes.status === 200) { if (mainRes.status === 200) {
const otherResponses = await Promise.all([ const emptyResponse: AxiosResponse<string> = {
httpGet(getStatsURL('ironman', rsn)).catch((err) => err), status: 404,
httpGet(getStatsURL('hardcore', rsn)).catch((err) => err), data: '',
httpGet(getStatsURL('ultimate', rsn)).catch((err) => err), statusText: '',
getRSNFormat(rsn).catch(() => undefined) headers: {},
]); config: {}
};
const [ironRes, hcRes, ultRes, formattedName] = otherResponses; const getModeStats = async (
mode: Extract<Gamemode, 'ironman' | 'hardcore' | 'ultimate'>
): Promise<AxiosResponse<string>> =>
otherGamemodes.includes(mode)
? httpGet<string>(getStatsURL(mode, rsn)).catch((err) => err)
: emptyResponse;
const formattedName = shouldGetFormattedRsn
? await getRSNFormat(rsn).catch(() => undefined)
: undefined;
const player: Player = { const player: Player = {
name: formattedName ?? rsn, name: formattedName ?? rsn,
@@ -192,8 +202,11 @@ export async function getStats(rsn: string): Promise<Player> {
}; };
player.main = parseStats(mainRes.data); player.main = parseStats(mainRes.data);
const ironRes = await getModeStats('ironman');
if (ironRes.status === 200) { if (ironRes.status === 200) {
player.ironman = parseStats(ironRes.data); player.ironman = parseStats(ironRes.data);
const hcRes = await getModeStats('hardcore');
const ultRes = await getModeStats('ultimate');
if (hcRes.status === 200) { if (hcRes.status === 200) {
player.mode = 'hardcore'; player.mode = 'hardcore';
player.hardcore = parseStats(hcRes.data); player.hardcore = parseStats(hcRes.data);
@@ -251,16 +264,11 @@ export async function getStatsByGamemode(
rsn: string, rsn: string,
mode: Gamemode = 'main' mode: Gamemode = 'main'
): Promise<Stats> { ): Promise<Stats> {
if (typeof rsn !== 'string') { validateRSN(rsn);
throw Error('RSN must be a string'); if (!GAMEMODES.includes(mode)) {
} else if (!/^[a-zA-Z0-9 _-]+$/.test(rsn)) {
throw Error('RSN contains invalid character');
} else if (rsn.length > 12 || rsn.length < 1) {
throw Error('RSN must be between 1 and 12 characters');
} else if (!GAMEMODES.includes(mode)) {
throw Error('Invalid game mode'); throw Error('Invalid game mode');
} }
const response = await httpGet(getStatsURL(mode, rsn)); const response = await httpGet<string>(getStatsURL(mode, rsn));
if (response.status !== 200) { if (response.status !== 200) {
throw Error('Player not found'); throw Error('Player not found');
} }
@@ -283,7 +291,7 @@ export async function getSkillPage(
} }
const url = getSkillPageURL(mode, skill, page); const url = getSkillPageURL(mode, skill, page);
const response = await httpGet(url); const response = await httpGet<string | Buffer | BinaryData | undefined>(url);
const dom = new JSDOM(response.data); const dom = new JSDOM(response.data);
const playersHTML = dom.window.document.querySelectorAll( const playersHTML = dom.window.document.querySelectorAll(
'.personal-hiscores__row' '.personal-hiscores__row'
@@ -331,7 +339,7 @@ export async function getActivityPage(
} }
const url = getActivityPageURL(mode, activity, page); const url = getActivityPageURL(mode, activity, page);
const response = await httpGet(url); const response = await httpGet<string | Buffer | BinaryData | undefined>(url);
const dom = new JSDOM(response.data); const dom = new JSDOM(response.data);
const playersHTML = dom.window.document.querySelectorAll( const playersHTML = dom.window.document.querySelectorAll(
'.personal-hiscores__row' '.personal-hiscores__row'

View File

@@ -166,3 +166,16 @@ export interface PlayerActivityRow extends Activity {
name: string; name: string;
dead: boolean; dead: boolean;
} }
export interface GetStatsOptions {
/**
* Other game modes to fetch ranks for.
* @defaultvalue `['ironman', 'hardcore', 'ultimate']`
*/
otherGamemodes?: Extract<Gamemode, 'ironman' | 'hardcore' | 'ultimate'>[];
/**
* If true, the formatted RSN will be fetched. Otherwise it will return the provided, unformatted RSN.
* @defaultvalue `true`
*/
shouldGetFormattedRsn?: boolean;
}