All files twitch-client.service.ts

84% Statements 21/25
100% Branches 0/0
80% Functions 4/5
82.6% Lines 19/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 851x 1x 1x   1x     1x     1x   4x 4x       1x         1x       1x 1x 1x                       1x       1x                                       1x 1x   1x       1x                          
import { HttpService } from '@nestjs/axios';
import { Inject, Injectable } from '@nestjs/common';
import { lastValueFrom } from 'rxjs';
import { TwitchClientOptions } from './twitch-client.options';
import {
  TWITCH_CLIENT_OPTS,
} from './twitch-client.token';
import { logError } from '@baneverywhere/error-handler';
 
@Injectable()
export class TwitchClientService {
  constructor(
    @Inject(TWITCH_CLIENT_OPTS) private readonly opts: TwitchClientOptions,
    private readonly http: HttpService
  ) {}
 
  async getAccessToken() {
    const { data } = await lastValueFrom(
      this.http.post<{ access_token: string }>(
        `https://id.twitch.tv/oauth2/token?client_id=${this.opts.clientID}&client_secret=${this.opts.clientSecret}&grant_type=client_credentials`
      )
    );
    return data.access_token;
  }
 
  @logError()
  public async findUsername(id: string) {
    const accessToken = await this.getAccessToken();
    const { data } = await lastValueFrom(
      this.http.get<{ data: Array<{ login: string }> }>(
        `https://api.twitch.tv/helix/users?id=${id}`,
        {
          headers: {
            'Client-ID': this.opts.clientID,
            Authorization: `Bearer ${accessToken}`,
          },
        }
      )
    );
 
    return data.data[0].login;
  }
 
  @logError()
  public async findUsernamesByLogin(logins: string[]) {
    const accessToken = await this.getAccessToken();
    const url = `https://api.twitch.tv/helix/users?login=${logins.join('&login=')}`;
 
    const { data } = await lastValueFrom(
      this.http.get<{ data: Array<{ id: string, login: string }> }>(
        url,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
            'Client-Id': this.opts.clientID,
          },
        }
      )
    );
 
    return data.data;
  }
 
  @logError()
  public async checkUsersStatus(logins: string[]) {
    const accessToken = await this.getAccessToken();
 
    const url = `https://api.twitch.tv/helix/streams?user_login=${logins.join(
      '&user_login='
    )}`;
 
    return await lastValueFrom(
      this.http.get<{ data: Array<{ user_login: string; type: string }> }>(
        url,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
            'Client-Id': this.opts.clientID,
          },
        }
      )
    );
  }
}