import { HttpException, HttpService, HttpStatus, Logger, Injectable, Inject } from '@nestjs/common'; import { AxiosRequestConfig } from 'axios'; import { LaunchpadApiClientAuthConfig } from '../../models/launchpad.auth.config'; import { LogBody } from '../../models/logbody'; @Injectable() export class LaunchpadApiService { constructor( private httpService: HttpService, @Inject('LAUNCHPAD_AUTH_CONFIG') private readonly authConfig: LaunchpadApiClientAuthConfig, ) {} async getUserByName(token: string): Promise { const requestUrl = this.authConfig.launchPadApiUrl + `/sso/userInfo`; // Prepare Request Options const requestOptions = { headers: { Authorization: `Bearer ${token}`, }, cache: { ignoreCache: true, }, } as AxiosRequestConfig; console.log('requesting:', requestUrl, requestOptions); try { const request = await this.httpService.get(requestUrl, requestOptions).toPromise(); console.log(request.status + request.statusText); if (request.status === 200 && request.data) { return request.data; } console.log( `Something when wrong when requesting user from launchpad: ${request.status} ${request.statusText}`, ); throw new HttpException( `Something when wrong when requesting user from launchpad: ${request.status} ${request.statusText}`, HttpStatus.FORBIDDEN, ); } catch (error) { console.log(`Encountered error getting user from launchpad: ${error}`); throw new HttpException( `Encountered error getting user from launchpad: ${error}`, HttpStatus.FORBIDDEN, ); } } async launchPadLog(log: LogBody): Promise { const token = this.authConfig.launchPadApiKey; const requestUrl = this.authConfig.launchPadApiUrl + `/sso/log`; this.httpService .post(requestUrl, log, { headers: { Authorization: `Bearer ${token}`, }, }) .toPromise() .then(() => { Logger.log('Logged to LaunchPad, success, log: ' + JSON.stringify(log)); }) .catch((error) => { console.log( 'Logged to LaunchPad, error, log: ' + JSON.stringify(log) + ', error: ' + JSON.stringify(error), ); }); } }