Skip to content

Commit

Permalink
refactor(*): improve code quality in PlayersService, use rxjs 9 syntax (
Browse files Browse the repository at this point in the history
  • Loading branch information
c43721 authored Sep 29, 2021
1 parent 25684da commit d8559bd
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 60 deletions.
9 changes: 5 additions & 4 deletions src/players/services/etf2l-profile.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
import { Etf2lProfile } from '../etf2l-profile';
import { switchMap, catchError } from 'rxjs/operators';
import { of, throwError } from 'rxjs';
import { firstValueFrom, of, throwError } from 'rxjs';
import { HttpService } from '@nestjs/axios';
import { NoEtf2lAccountError } from '../errors/no-etf2l-account.error';

Expand All @@ -21,7 +21,7 @@ export class Etf2lProfileService {

// TODO This is steamId or etf2lProfileId
async fetchPlayerInfo(steamId: string): Promise<Etf2lProfile> {
return this.httpService
const profile = this.httpService
.get<Etf2lPlayerResponse>(`${this.etf2lEndpoint}/player/${steamId}.json`)
.pipe(
catchError((error) => {
Expand Down Expand Up @@ -51,7 +51,8 @@ export class Etf2lProfileService {
}
}
}),
)
.toPromise();
);

return await firstValueFrom(profile);
}
}
60 changes: 22 additions & 38 deletions src/players/services/players.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import { Events } from '@/events/events';
import { plainToClass } from 'class-transformer';
import { Tf2ClassName } from '@/shared/models/tf2-class-name';
import { Error, Model, Types, UpdateQuery } from 'mongoose';
import { Tf2InGameHoursVerificationError } from '../errors/tf2-in-game-hours-verification.error';
import { AccountBannedError } from '../errors/account-banned.error';
import { InsufficientTf2InGameHoursError } from '../errors/insufficient-tf2-in-game-hours.error';
import { PlayerRole } from '../models/player-role';
Expand Down Expand Up @@ -119,7 +118,10 @@ export class PlayersService implements OnModuleInit {
let etf2lProfile: Etf2lProfile;
let name = steamProfile.displayName;

try {
const { value: isEtf2lAccountRequired } =
await this.configurationService.isEtf2lAccountRequired();

if (isEtf2lAccountRequired) {
etf2lProfile = await this.etf2lProfileService.fetchPlayerInfo(
steamProfile.id,
);
Expand All @@ -132,13 +134,6 @@ export class PlayersService implements OnModuleInit {
}

name = etf2lProfile.name;
} catch (error) {
const isEtf2lAccountRequired = (
await this.configurationService.isEtf2lAccountRequired()
).value;
if (isEtf2lAccountRequired) {
throw error;
}
}

const avatar: PlayerAvatar = {
Expand Down Expand Up @@ -173,19 +168,15 @@ export class PlayersService implements OnModuleInit {
async forceCreatePlayer(
playerData: ForceCreatePlayerOptions,
): Promise<Player> {
let etf2lProfile: Etf2lProfile;
try {
etf2lProfile = await this.etf2lProfileService.fetchPlayerInfo(
playerData.steamId,
);
} catch (error) {
etf2lProfile = undefined;
}
const etf2lProfile = await this.etf2lProfileService
.fetchPlayerInfo(playerData.steamId)
.catch(() => undefined);

const { id } = await this.playerModel.create({
etf2lProfileId: etf2lProfile?.id,
...playerData,
});

const player = await this.getById(id);
this.logger.verbose(`created new player (name: ${player.name})`);
this.events.playerRegisters.next({ player });
Expand Down Expand Up @@ -232,27 +223,20 @@ export class PlayersService implements OnModuleInit {
}

private async verifyTf2InGameHours(steamId: string) {
const minimumTf2InGameHours = (
await this.configurationService.getMinimumTf2InGameHours()
).value;
try {
const hoursInTf2 = await this.steamApiService.getTf2InGameHours(steamId);
if (hoursInTf2 < minimumTf2InGameHours) {
throw new InsufficientTf2InGameHoursError(
steamId,
minimumTf2InGameHours,
hoursInTf2,
);
}
} catch (error) {
if (
error instanceof Tf2InGameHoursVerificationError &&
minimumTf2InGameHours <= 0
) {
return;
} else {
throw error;
}
const { value: minimumTf2InGameHours } =
await this.configurationService.getMinimumTf2InGameHours();

if (minimumTf2InGameHours <= 0) {
return;
}

const hoursInTf2 = await this.steamApiService.getTf2InGameHours(steamId);
if (hoursInTf2 < minimumTf2InGameHours) {
throw new InsufficientTf2InGameHoursError(
steamId,
minimumTf2InGameHours,
hoursInTf2,
);
}
}
}
9 changes: 5 additions & 4 deletions src/players/services/steam-api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
import { Environment } from '@/environment/environment';
import { map, switchMap, catchError } from 'rxjs/operators';
import { floor } from 'lodash';
import { of, throwError } from 'rxjs';
import { firstValueFrom, of, throwError } from 'rxjs';
import { Tf2InGameHoursVerificationError } from '../errors/tf2-in-game-hours-verification.error';
import { HttpService } from '@nestjs/axios';

Expand All @@ -28,7 +28,7 @@ export class SteamApiService {
) {}

async getTf2InGameHours(steamId64: string): Promise<number> {
return this.httpService
const hours = this.httpService
.get<UserStatsForGameResponse>(
`${this.userStatsForGameEndpoint}/?appid=${this.tf2AppId}&key=${this.environment.steamApiKey}&steamid=${steamId64}&format=json`,
)
Expand All @@ -46,7 +46,8 @@ export class SteamApiService {
() => new Tf2InGameHoursVerificationError(steamId64, error),
),
),
)
.toPromise();
);

return await firstValueFrom(hours);
}
}
17 changes: 10 additions & 7 deletions src/plugins/twitch/services/twitch-auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';
import { Environment } from '@/environment/environment';
import { map } from 'rxjs/operators';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';

interface TokenResponse {
access_token: string;
Expand Down Expand Up @@ -47,7 +48,7 @@ export class TwitchAuthService {
}

async fetchUserAccessToken(code: string) {
return this.httpService
const token = this.httpService
.post<TokenResponse>(
`${twitchOauth2TokenUrl}` +
`?client_id=${this.environment.twitchClientId}` +
Expand All @@ -56,8 +57,9 @@ export class TwitchAuthService {
`&grant_type=authorization_code` +
`&redirect_uri=${this.redirectUri}`,
)
.pipe(map((response) => response.data.access_token))
.toPromise();
.pipe(map((response) => response.data.access_token));

return await firstValueFrom(token);
}

async getAppAccessToken() {
Expand All @@ -80,8 +82,8 @@ export class TwitchAuthService {
return this.appAccessToken;
}

private fetchAppAccessToken() {
return this.httpService
private async fetchAppAccessToken() {
const appAccess = this.httpService
.post<AppAccessTokenResponse>(
twitchOauth2TokenUrl,
{},
Expand All @@ -98,7 +100,8 @@ export class TwitchAuthService {
accessToken: response.data.access_token,
expiresIn: response.data.expires_in,
})),
)
.toPromise();
);

return await firstValueFrom(appAccess);
}
}
18 changes: 11 additions & 7 deletions src/plugins/twitch/services/twitch.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { TwitchStream } from '../models/twitch-stream';
import { Cron, CronExpression } from '@nestjs/schedule';
import { Environment } from '@/environment/environment';
import { map, distinctUntilChanged } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs';
import { BehaviorSubject, firstValueFrom } from 'rxjs';
import { TwitchGateway } from '../gateways/twitch.gateway';
import { TwitchAuthService } from './twitch-auth.service';
import { PlayerBansService } from '@/players/services/player-bans.service';
Expand Down Expand Up @@ -103,15 +103,16 @@ export class TwitchService implements OnModuleInit {

async fetchUserProfile(accessToken: string) {
// https://dev.twitch.tv/docs/api/reference#get-users
return this.httpService
const token = this.httpService
.get<TwitchGetUsersResponse>(`${twitchTvApiEndpoint}/users`, {
headers: {
Authorization: `Bearer ${accessToken}`,
'Client-ID': this.environment.twitchClientId,
},
})
.pipe(map((response) => response.data.data[0]))
.toPromise();
.pipe(map((response) => response.data.data[0]));

return await firstValueFrom(token);
}

async saveUserProfile(playerId: string, code: string) {
Expand Down Expand Up @@ -147,6 +148,7 @@ export class TwitchService implements OnModuleInit {
userIds: users.map((user) => user.userId),
userLogins: promotedStreams,
});

const streams = (
await Promise.all(
rawStreams.map(async (stream) => {
Expand Down Expand Up @@ -184,6 +186,7 @@ export class TwitchService implements OnModuleInit {
}),
)
).filter((stream) => !!stream);

this._streams.next(streams);
this.logger.debug('streams refreshed');
}
Expand All @@ -193,7 +196,7 @@ export class TwitchService implements OnModuleInit {
userLogins: string[];
}) {
// https://dev.twitch.tv/docs/api/reference#get-streams
return this.httpService
const streams = this.httpService
.get<TwitchGetStreamsResponse>(`${twitchTvApiEndpoint}/streams`, {
params: {
user_id: params.userIds,
Expand All @@ -204,7 +207,8 @@ export class TwitchService implements OnModuleInit {
Authorization: `Bearer ${await this.twitchAuthService.getAppAccessToken()}`,
},
})
.pipe(map((response) => response.data.data))
.toPromise();
.pipe(map((response) => response.data.data));

return await firstValueFrom(streams);
}
}

0 comments on commit d8559bd

Please sign in to comment.