Skip to content

Commit

Permalink
🔨 refactor axios/apiRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
idinium96 committed May 5, 2024
1 parent 4173f85 commit a4a433d
Show file tree
Hide file tree
Showing 15 changed files with 185 additions and 204 deletions.
14 changes: 4 additions & 10 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ import { apiRequest } from './lib/apiRequest';

/*eslint-disable */
SchemaManager.prototype.getSchema = function (callback): void {
apiRequest('GET', 'https://schema.autobot.tf/schema')
apiRequest({ method: 'GET', url: 'https://schema.autobot.tf/schema' })
.then(schema => {
this.setSchema(schema, true);
callback(null, this.schema);
Expand All @@ -86,9 +86,7 @@ const botManager = new BotManager(
import ON_DEATH from 'death';
import * as inspect from 'util';
import { Webhook } from './classes/DiscordWebhook/interfaces';
import axios, { AxiosError } from 'axios';
import { uptime } from './lib/tools/time';
import filterAxiosError from '@tf2autobot/filter-axios-error';

ON_DEATH({ uncaughtException: true })((signalOrErr, origin: string | Error) => {
const crashed = !['SIGINT', 'SIGTERM'].includes(signalOrErr as 'SIGINT' | 'SIGTERM' | 'SIGQUIT');
Expand Down Expand Up @@ -143,13 +141,9 @@ ON_DEATH({ uncaughtException: true })((signalOrErr, origin: string | Error) => {
]
};

void axios({
method: 'POST',
url: optDW.sendAlert.url.main,
data: sendAlertWebhook // axios should automatically set Content-Type header to application/json
}).catch((err: AxiosError) => {
log.error('Error sending webhook on crash', filterAxiosError(err));
});
apiRequest({ method: 'POST', url: optDW.sendAlert.url.main, data: sendAlertWebhook }).catch(err =>
log.error('Error sending webhook on crash', err)
);
}

if (botReady) {
Expand Down
27 changes: 15 additions & 12 deletions src/classes/Bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import TF2 from '@tf2autobot/tf2';
import dayjs, { Dayjs } from 'dayjs';
import async from 'async';
import semver from 'semver';
import axios, { AxiosError } from 'axios';
import { AxiosError } from 'axios';
import pluralize from 'pluralize';
import * as timersPromises from 'timers/promises';
import fs from 'fs';
Expand Down Expand Up @@ -44,6 +44,7 @@ import { EventEmitter } from 'events';
import { Blocked } from './MyHandler/interfaces';
import filterAxiosError from '@tf2autobot/filter-axios-error';
import { axiosAbortSignal } from '../lib/helpers';
import { apiRequest } from '../lib/apiRequest';

export interface SteamTokens {
refreshToken: string;
Expand Down Expand Up @@ -312,13 +313,12 @@ export default class Bot {

private getLocalizationFile(attempt: 'first' | 'retry' = 'first'): Promise<void> {
return new Promise((resolve, reject) => {
axios({
method: 'get',
apiRequest<string>({
method: 'GET',
url: `https://raw.githubusercontent.com/SteamDatabase/GameTracking-TF2/master/tf/resource/tf_${this.options.tf2Language}.txt`,
signal: axiosAbortSignal(60000)
})
.then(response => {
const content = response.data as string;
.then(content => {
this.tf2.setLang(content);
return resolve();
})
Expand Down Expand Up @@ -548,26 +548,23 @@ export default class Bot {
attempt: 'first' | 'retry' = 'first'
): Promise<{ version: string; canUpdateRepo: boolean; updateMessage: string }> {
return new Promise((resolve, reject) => {
void axios({
apiRequest<GithubPackageJson>({
method: 'GET',
url: 'https://raw.githubusercontent.com/TF2Autobot/tf2autobot/master/package.json',
signal: axiosAbortSignal(60000)
})
.then(response => {
/*eslint-disable */
const data = response.data;
.then(data => {
return resolve({
version: data.version,
canUpdateRepo: data.updaterepo,
updateMessage: data.updateMessage
});
/*eslint-enable */
})
.catch((err: AxiosError) => {
.catch(err => {
if (err instanceof AbortSignal && attempt !== 'retry') {
return this.getLatestVersion('retry');
}
reject(filterAxiosError(err));
reject(err);
});
});
}
Expand Down Expand Up @@ -1721,3 +1718,9 @@ export default class Bot {
return fs.existsSync(path.resolve(__dirname, '..', '..', '.git'));
}
}

interface GithubPackageJson {
version: string;
updaterepo: boolean;
updateMessage: string;
}
21 changes: 8 additions & 13 deletions src/classes/Carts/Cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ import dayjs from 'dayjs';
import SKU from '@tf2autobot/tf2-sku';
import TradeOfferManager, { OurTheirItemsDict, TradeOffer } from '@tf2autobot/tradeoffer-manager';
import pluralize from 'pluralize';
import axios, { AxiosError } from 'axios';
import { UnknownDictionary } from '../../types/common';
import Bot from '../Bot';
import Pricelist from '../Pricelist';
import { BPTFGetUserInfo } from '../MyHandler/interfaces';
import log from '../../lib/logger';
import { sendAlert } from '../DiscordWebhook/export';
import filterAxiosError from '@tf2autobot/filter-axios-error';
import { apiRequest } from '../../lib/apiRequest';

/**
* An abstract class used for sending offers
Expand Down Expand Up @@ -569,9 +568,9 @@ export default abstract class Cart {

private async getTotalBackpackSlots(steamID64: string): Promise<number> {
return new Promise(resolve => {
void axios({
url: 'https://api.backpack.tf/api/users/info/v1',
apiRequest<BPTFGetUserInfo>({
method: 'GET',
url: 'https://api.backpack.tf/api/users/info/v1',
headers: {
'User-Agent': 'TF2Autobot@' + process.env.BOT_VERSION,
Cookie: 'user-id=' + this.bot.userID
Expand All @@ -581,19 +580,15 @@ export default abstract class Cart {
steamids: steamID64
}
})
.then(response => {
const thisBody = response.data as BPTFGetUserInfo;

const user = thisBody.users[steamID64];
.then(body => {
const user = body.users[steamID64];
const totalBackpackSlots = user.inventory ? user.inventory['440'].slots.total : 0;

return resolve(totalBackpackSlots);
})
.catch((err: AxiosError) => {
if (err) {
log.error('Failed requesting user info from backpack.tf: ', filterAxiosError(err));
return resolve(0);
}
.catch(err => {
log.error('Failed requesting user info from backpack.tf: ', err);
return resolve(0);
});
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/classes/Carts/CartQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export default class CartQueue {
// determine whether it's good time to restart or not
try {
// test if backpack.tf is alive by performing bptf banned check request
await isBptfBanned(steamID, this.bot.options.bptfApiKey, this.bot.userID);
await isBptfBanned({ steamID, bptfApiKey: this.bot.options.bptfApiKey, userID: this.bot.userID });
} catch (err) {
// do not restart, try again after 3 minutes
clearTimeout(this.queuePositionCheck);
Expand Down
13 changes: 5 additions & 8 deletions src/classes/Commands/Commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ import { fixItem } from '../../lib/items';
import { UnknownDictionary } from '../../types/common';
import log from '../../lib/logger';
import { testPriceKey } from '../../lib/tools/export';
import axios, { AxiosError } from 'axios';
import filterAxiosError from '@tf2autobot/filter-axios-error';
import { apiRequest } from '../../lib/apiRequest';

type Instant = 'buy' | 'b' | 'sell' | 's';
type CraftUncraft = 'craftweapon' | 'uncraftweapon';
Expand Down Expand Up @@ -1465,7 +1464,7 @@ const paintCanDefindexes = [

function getMptfDashboardItems(mptfApiKey: string, ignorePainted = false): Promise<GetMptfDashboardItemsReturn> {
return new Promise((resolve, reject) => {
void axios({
apiRequest<GetMptfDashboardItems>({
method: 'GET',
url: 'https://marketplace.tf/api/Seller/GetDashboardItems/v2',
headers: {
Expand All @@ -1475,9 +1474,7 @@ function getMptfDashboardItems(mptfApiKey: string, ignorePainted = false): Promi
key: mptfApiKey
}
})
.then(response => {
const body = response.data as GetMptfDashboardItems;

.then(body => {
if (body.success === false) {
return reject(body);
}
Expand Down Expand Up @@ -1508,8 +1505,8 @@ function getMptfDashboardItems(mptfApiKey: string, ignorePainted = false): Promi

return resolve(toReturn);
})
.catch((err: AxiosError) => {
reject(filterAxiosError(err));
.catch(err => {
reject(err);
});
});
}
Expand Down
19 changes: 6 additions & 13 deletions src/classes/DiscordWebhook/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import TradeOfferManager, { TradeOffer } from '@tf2autobot/tradeoffer-manager';
import axios, { AxiosError } from 'axios';
import { Webhook } from './interfaces';
import Bot from '../Bot';
import log from '../../lib/logger';
import filterAxiosError, { ErrorFiltered } from '@tf2autobot/filter-axios-error';
import { AxiosError } from 'axios';
import { ErrorFiltered } from '@tf2autobot/filter-axios-error';
import { apiRequest } from '../../lib/apiRequest';

export function getPartnerDetails(offer: TradeOffer, bot: Bot): Promise<{ personaName: string; avatarFull: any }> {
return new Promise(resolve => {
Expand Down Expand Up @@ -58,17 +59,9 @@ export function sendWebhook(url: string, webhook: Webhook, event: string, i?: nu
});
}

void axios({
method: 'POST',
url: url,
data: webhook
})
.then(() => {
resolve();
})
.catch((err: AxiosError) => {
reject({ err: filterAxiosError(err), webhook });
});
apiRequest({ method: 'POST', url, data: webhook })
.then(() => resolve())
.catch((err: AxiosError) => reject({ err, webhook }));
});
}

Expand Down
42 changes: 27 additions & 15 deletions src/classes/Friends.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { EFriendRelationship } from 'steam-user';
import SteamID from 'steamid';
import axios, { AxiosError } from 'axios';
import Bot from './Bot';
import filterAxiosError from '@tf2autobot/filter-axios-error';
import { SteamRequestParams } from '../types/common';
import { apiRequest } from '../lib/apiRequest';

export default class Friends {
maxFriends: number | undefined;
Expand Down Expand Up @@ -53,28 +52,21 @@ export default class Friends {
const hasApiKey = !!this.bot.manager.apiKey;
params[hasApiKey ? 'key' : 'access_token'] = this.bot.manager[hasApiKey ? 'apiKey' : 'accessToken'];

axios({
url: 'https://api.steampowered.com/IPlayerService/GetBadges/v1/',
apiRequest<GetBadges>({
method: 'GET',
url: 'https://api.steampowered.com/IPlayerService/GetBadges/v1/',
params
})
.then(response => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
const result = response.data.response;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
.then(body => {
const result = body.response;
const level = result.player_level;

const base = 250;
const multiplier = 5;

this.maxFriends = base + level * multiplier;

resolve(this.maxFriends);
})
.catch((err: AxiosError) => {
if (err) {
return reject(filterAxiosError(err));
}
.catch(err => {
return reject(err);
});
});
}
Expand All @@ -91,3 +83,23 @@ interface Friend {
avatar_url_medium: string;
avatar_url_full: string;
}

interface GetBadges {
response: ResponseGetBadges;
}

interface ResponseGetBadges {
badges: BadgesGetBadges[];
player_xp: number;
player_level: number;
player_xp_needed_to_level_up: number;
player_xp_needed_current_level: number;
}

interface BadgesGetBadges {
badgeid: number;
level: number;
completion_time: number;
xp: number;
scarcity: number;
}
9 changes: 4 additions & 5 deletions src/classes/InventoryApis/InventoryApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { UnknownDictionary, UnknownDictionaryKnownValues } from 'src/types/commo
import SteamID from 'steamid';
import CEconItem from '@tf2autobot/steamcommunity/classes/CEconItem';
import { EconItem } from '@tf2autobot/tradeoffer-manager';

import Bot from '../Bot';

export default class InventoryApi {
Expand Down Expand Up @@ -52,9 +51,9 @@ export default class InventoryApi {

const userSteamID64 = typeof userID === 'string' ? userID : userID.getSteamID64();

const [apiCallURL, apiCallParams] = this.getURLAndParams(userSteamID64, appID, contextID);
const [apiCallUrl, apiCallParams] = this.getURLAndParams(userSteamID64, appID, contextID);

if (apiCallURL === '') {
if (apiCallUrl === '') {
callback(new Error('Improper usage of InventoryAPI; descendant class should define getURLAndParams'));
return;
}
Expand All @@ -63,8 +62,8 @@ export default class InventoryApi {
get([], []);

function get(inventory: EconItem[], currency: EconItem[], start?: string) {
void axios({
url: apiCallURL,
axios({
url: apiCallUrl,
params: {
...apiCallParams,
start_assetid: start
Expand Down
Loading

0 comments on commit a4a433d

Please sign in to comment.