All files AuthClient.ts

88.57% Statements 31/35
93.33% Branches 14/15
76.92% Functions 10/13
93.33% Lines 28/30

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  1x 6x 6x 4x 2x 10x 6x     1x 1x 1x 1x 1x 1x 6x   1x     10x 10x 10x     10x 1x           1x     1x           6x 6x           6x 6x 4x       1x      
import axios from 'axios';
import { requestLogger, responseLogger } from 'axios-logger';
import {v4} from 'uuid'
 
const btoa = (str: string) => {
  return Buffer.from(str).toString('base64');
}
 
export interface IAuthClientOptions {
  debug: boolean;
  url?: string;
  logger?: any;
}
 
const AUTH_URL = 'https://ngw.devices.sberbank.ru:9443';
 
export class AuthClient{
  axios: any;
  client_id: string;
  client_secret: string;
 
  constructor(client_id: string, client_secret: string, options: IAuthClientOptions){
    this.client_id = client_id;
    this.client_secret = client_secret;
 
    this.axios = axios.create({
      baseURL: options.url || AUTH_URL,
    })
 
    if (options.debug) {
      const config = {
        prefixText: 'GigachatAuthClient',
        status: true,
        headers: false,
        params: true,
      };
      this.axios.interceptors.request.use((request: any) => {
        return requestLogger(request, config);
      });
      this.axios.interceptors.response.use((response: any) => {
        return responseLogger(response, config);
      });
    } 
  }
 
  async getToken(scope: string){
    const headers = {
      authorization: 'Basic ' + btoa(this.client_id + ':' + this.client_secret),
      rquid: v4(),
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
    };
    const url = '/api/v2/oauth';
 
    const response = await this.axios.post(url, {scope}, {headers});
    return response.data;
  }
}