Skip to content

Commit a4a433d

Browse files
committed
🔨 refactor axios/apiRequest
1 parent 4173f85 commit a4a433d

File tree

15 files changed

+185
-204
lines changed

15 files changed

+185
-204
lines changed

src/app.ts

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ import { apiRequest } from './lib/apiRequest';
6464

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

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

146-
void axios({
147-
method: 'POST',
148-
url: optDW.sendAlert.url.main,
149-
data: sendAlertWebhook // axios should automatically set Content-Type header to application/json
150-
}).catch((err: AxiosError) => {
151-
log.error('Error sending webhook on crash', filterAxiosError(err));
152-
});
144+
apiRequest({ method: 'POST', url: optDW.sendAlert.url.main, data: sendAlertWebhook }).catch(err =>
145+
log.error('Error sending webhook on crash', err)
146+
);
153147
}
154148

155149
if (botReady) {

src/classes/Bot.ts

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import TF2 from '@tf2autobot/tf2';
1111
import dayjs, { Dayjs } from 'dayjs';
1212
import async from 'async';
1313
import semver from 'semver';
14-
import axios, { AxiosError } from 'axios';
14+
import { AxiosError } from 'axios';
1515
import pluralize from 'pluralize';
1616
import * as timersPromises from 'timers/promises';
1717
import fs from 'fs';
@@ -44,6 +44,7 @@ import { EventEmitter } from 'events';
4444
import { Blocked } from './MyHandler/interfaces';
4545
import filterAxiosError from '@tf2autobot/filter-axios-error';
4646
import { axiosAbortSignal } from '../lib/helpers';
47+
import { apiRequest } from '../lib/apiRequest';
4748

4849
export interface SteamTokens {
4950
refreshToken: string;
@@ -312,13 +313,12 @@ export default class Bot {
312313

313314
private getLocalizationFile(attempt: 'first' | 'retry' = 'first'): Promise<void> {
314315
return new Promise((resolve, reject) => {
315-
axios({
316-
method: 'get',
316+
apiRequest<string>({
317+
method: 'GET',
317318
url: `https://raw.githubusercontent.com/SteamDatabase/GameTracking-TF2/master/tf/resource/tf_${this.options.tf2Language}.txt`,
318319
signal: axiosAbortSignal(60000)
319320
})
320-
.then(response => {
321-
const content = response.data as string;
321+
.then(content => {
322322
this.tf2.setLang(content);
323323
return resolve();
324324
})
@@ -548,26 +548,23 @@ export default class Bot {
548548
attempt: 'first' | 'retry' = 'first'
549549
): Promise<{ version: string; canUpdateRepo: boolean; updateMessage: string }> {
550550
return new Promise((resolve, reject) => {
551-
void axios({
551+
apiRequest<GithubPackageJson>({
552552
method: 'GET',
553553
url: 'https://raw.githubusercontent.com/TF2Autobot/tf2autobot/master/package.json',
554554
signal: axiosAbortSignal(60000)
555555
})
556-
.then(response => {
557-
/*eslint-disable */
558-
const data = response.data;
556+
.then(data => {
559557
return resolve({
560558
version: data.version,
561559
canUpdateRepo: data.updaterepo,
562560
updateMessage: data.updateMessage
563561
});
564-
/*eslint-enable */
565562
})
566-
.catch((err: AxiosError) => {
563+
.catch(err => {
567564
if (err instanceof AbortSignal && attempt !== 'retry') {
568565
return this.getLatestVersion('retry');
569566
}
570-
reject(filterAxiosError(err));
567+
reject(err);
571568
});
572569
});
573570
}
@@ -1721,3 +1718,9 @@ export default class Bot {
17211718
return fs.existsSync(path.resolve(__dirname, '..', '..', '.git'));
17221719
}
17231720
}
1721+
1722+
interface GithubPackageJson {
1723+
version: string;
1724+
updaterepo: boolean;
1725+
updateMessage: string;
1726+
}

src/classes/Carts/Cart.ts

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,13 @@ import dayjs from 'dayjs';
33
import SKU from '@tf2autobot/tf2-sku';
44
import TradeOfferManager, { OurTheirItemsDict, TradeOffer } from '@tf2autobot/tradeoffer-manager';
55
import pluralize from 'pluralize';
6-
import axios, { AxiosError } from 'axios';
76
import { UnknownDictionary } from '../../types/common';
87
import Bot from '../Bot';
98
import Pricelist from '../Pricelist';
109
import { BPTFGetUserInfo } from '../MyHandler/interfaces';
1110
import log from '../../lib/logger';
1211
import { sendAlert } from '../DiscordWebhook/export';
13-
import filterAxiosError from '@tf2autobot/filter-axios-error';
12+
import { apiRequest } from '../../lib/apiRequest';
1413

1514
/**
1615
* An abstract class used for sending offers
@@ -569,9 +568,9 @@ export default abstract class Cart {
569568

570569
private async getTotalBackpackSlots(steamID64: string): Promise<number> {
571570
return new Promise(resolve => {
572-
void axios({
573-
url: 'https://api.backpack.tf/api/users/info/v1',
571+
apiRequest<BPTFGetUserInfo>({
574572
method: 'GET',
573+
url: 'https://api.backpack.tf/api/users/info/v1',
575574
headers: {
576575
'User-Agent': 'TF2Autobot@' + process.env.BOT_VERSION,
577576
Cookie: 'user-id=' + this.bot.userID
@@ -581,19 +580,15 @@ export default abstract class Cart {
581580
steamids: steamID64
582581
}
583582
})
584-
.then(response => {
585-
const thisBody = response.data as BPTFGetUserInfo;
586-
587-
const user = thisBody.users[steamID64];
583+
.then(body => {
584+
const user = body.users[steamID64];
588585
const totalBackpackSlots = user.inventory ? user.inventory['440'].slots.total : 0;
589586

590587
return resolve(totalBackpackSlots);
591588
})
592-
.catch((err: AxiosError) => {
593-
if (err) {
594-
log.error('Failed requesting user info from backpack.tf: ', filterAxiosError(err));
595-
return resolve(0);
596-
}
589+
.catch(err => {
590+
log.error('Failed requesting user info from backpack.tf: ', err);
591+
return resolve(0);
597592
});
598593
});
599594
}

src/classes/Carts/CartQueue.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ export default class CartQueue {
6767
// determine whether it's good time to restart or not
6868
try {
6969
// test if backpack.tf is alive by performing bptf banned check request
70-
await isBptfBanned(steamID, this.bot.options.bptfApiKey, this.bot.userID);
70+
await isBptfBanned({ steamID, bptfApiKey: this.bot.options.bptfApiKey, userID: this.bot.userID });
7171
} catch (err) {
7272
// do not restart, try again after 3 minutes
7373
clearTimeout(this.queuePositionCheck);

src/classes/Commands/Commands.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,7 @@ import { fixItem } from '../../lib/items';
2121
import { UnknownDictionary } from '../../types/common';
2222
import log from '../../lib/logger';
2323
import { testPriceKey } from '../../lib/tools/export';
24-
import axios, { AxiosError } from 'axios';
25-
import filterAxiosError from '@tf2autobot/filter-axios-error';
24+
import { apiRequest } from '../../lib/apiRequest';
2625

2726
type Instant = 'buy' | 'b' | 'sell' | 's';
2827
type CraftUncraft = 'craftweapon' | 'uncraftweapon';
@@ -1465,7 +1464,7 @@ const paintCanDefindexes = [
14651464

14661465
function getMptfDashboardItems(mptfApiKey: string, ignorePainted = false): Promise<GetMptfDashboardItemsReturn> {
14671466
return new Promise((resolve, reject) => {
1468-
void axios({
1467+
apiRequest<GetMptfDashboardItems>({
14691468
method: 'GET',
14701469
url: 'https://marketplace.tf/api/Seller/GetDashboardItems/v2',
14711470
headers: {
@@ -1475,9 +1474,7 @@ function getMptfDashboardItems(mptfApiKey: string, ignorePainted = false): Promi
14751474
key: mptfApiKey
14761475
}
14771476
})
1478-
.then(response => {
1479-
const body = response.data as GetMptfDashboardItems;
1480-
1477+
.then(body => {
14811478
if (body.success === false) {
14821479
return reject(body);
14831480
}
@@ -1508,8 +1505,8 @@ function getMptfDashboardItems(mptfApiKey: string, ignorePainted = false): Promi
15081505

15091506
return resolve(toReturn);
15101507
})
1511-
.catch((err: AxiosError) => {
1512-
reject(filterAxiosError(err));
1508+
.catch(err => {
1509+
reject(err);
15131510
});
15141511
});
15151512
}

src/classes/DiscordWebhook/utils.ts

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import TradeOfferManager, { TradeOffer } from '@tf2autobot/tradeoffer-manager';
2-
import axios, { AxiosError } from 'axios';
32
import { Webhook } from './interfaces';
43
import Bot from '../Bot';
54
import log from '../../lib/logger';
6-
import filterAxiosError, { ErrorFiltered } from '@tf2autobot/filter-axios-error';
5+
import { AxiosError } from 'axios';
6+
import { ErrorFiltered } from '@tf2autobot/filter-axios-error';
7+
import { apiRequest } from '../../lib/apiRequest';
78

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

61-
void axios({
62-
method: 'POST',
63-
url: url,
64-
data: webhook
65-
})
66-
.then(() => {
67-
resolve();
68-
})
69-
.catch((err: AxiosError) => {
70-
reject({ err: filterAxiosError(err), webhook });
71-
});
62+
apiRequest({ method: 'POST', url, data: webhook })
63+
.then(() => resolve())
64+
.catch((err: AxiosError) => reject({ err, webhook }));
7265
});
7366
}
7467

src/classes/Friends.ts

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import { EFriendRelationship } from 'steam-user';
22
import SteamID from 'steamid';
3-
import axios, { AxiosError } from 'axios';
43
import Bot from './Bot';
5-
import filterAxiosError from '@tf2autobot/filter-axios-error';
64
import { SteamRequestParams } from '../types/common';
5+
import { apiRequest } from '../lib/apiRequest';
76

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

56-
axios({
57-
url: 'https://api.steampowered.com/IPlayerService/GetBadges/v1/',
55+
apiRequest<GetBadges>({
5856
method: 'GET',
57+
url: 'https://api.steampowered.com/IPlayerService/GetBadges/v1/',
5958
params
6059
})
61-
.then(response => {
62-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
63-
const result = response.data.response;
64-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
60+
.then(body => {
61+
const result = body.response;
6562
const level = result.player_level;
66-
6763
const base = 250;
6864
const multiplier = 5;
69-
7065
this.maxFriends = base + level * multiplier;
71-
7266
resolve(this.maxFriends);
7367
})
74-
.catch((err: AxiosError) => {
75-
if (err) {
76-
return reject(filterAxiosError(err));
77-
}
68+
.catch(err => {
69+
return reject(err);
7870
});
7971
});
8072
}
@@ -91,3 +83,23 @@ interface Friend {
9183
avatar_url_medium: string;
9284
avatar_url_full: string;
9385
}
86+
87+
interface GetBadges {
88+
response: ResponseGetBadges;
89+
}
90+
91+
interface ResponseGetBadges {
92+
badges: BadgesGetBadges[];
93+
player_xp: number;
94+
player_level: number;
95+
player_xp_needed_to_level_up: number;
96+
player_xp_needed_current_level: number;
97+
}
98+
99+
interface BadgesGetBadges {
100+
badgeid: number;
101+
level: number;
102+
completion_time: number;
103+
xp: number;
104+
scarcity: number;
105+
}

src/classes/InventoryApis/InventoryApi.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { UnknownDictionary, UnknownDictionaryKnownValues } from 'src/types/commo
44
import SteamID from 'steamid';
55
import CEconItem from '@tf2autobot/steamcommunity/classes/CEconItem';
66
import { EconItem } from '@tf2autobot/tradeoffer-manager';
7-
87
import Bot from '../Bot';
98

109
export default class InventoryApi {
@@ -52,9 +51,9 @@ export default class InventoryApi {
5251

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

55-
const [apiCallURL, apiCallParams] = this.getURLAndParams(userSteamID64, appID, contextID);
54+
const [apiCallUrl, apiCallParams] = this.getURLAndParams(userSteamID64, appID, contextID);
5655

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

6564
function get(inventory: EconItem[], currency: EconItem[], start?: string) {
66-
void axios({
67-
url: apiCallURL,
65+
axios({
66+
url: apiCallUrl,
6867
params: {
6968
...apiCallParams,
7069
start_assetid: start

0 commit comments

Comments
 (0)