Untitled
unknown
plain_text
a year ago
3.2 kB
3
Indexable
Never
import { Injectable } from '@nestjs/common'; import { firstValueFrom } from 'rxjs'; import { HttpService } from '@nestjs/axios'; @Injectable() export class StubhubService { private clientId = '9YxHBeR2nXxzvdQu4HVZ'; private clientSecret = 'uScf4sLEEMFH5KL3suOUEFVqhDZu9c5Fy8Ar5RMSSMxaSp4lRWBK3BVo6w71'; private authorizationHeader: string = Buffer.from( `${this.clientId}:${this.clientSecret}`, ).toString('base64'); private accessToken!: string; private lastUpdateTimeStampOfAccessToken!: number; private timeStampExpiresIn!: number; constructor(private readonly httpService: HttpService) { this.updateAccessToken(); } public async updateAccessToken(): Promise<void> { const response = await firstValueFrom( this.httpService.post( 'https://account.stubhub.com/oauth2/token', { grant_type: 'client_credentials', scope: 'read:events' }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: `Basic ${this.authorizationHeader}`, }, }, ), ); const { expires_in, access_token } = response.data; this.timeStampExpiresIn = expires_in; this.lastUpdateTimeStampOfAccessToken = new Date().valueOf() / 1000; this.accessToken = access_token; } public async searchEventsByQuery(query: string): Promise<any> { if (this.isAccessTokenExpired()) { this.updateAccessToken(); } try { const response = await firstValueFrom( this.httpService.get(`https://api.viagogo.net/catalog/events/search`, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: `Bearer ${this.accessToken}`, }, params: { q: query, // page: 0, page_size: 1000, dateLocal: '2024-06-21', // updated_since: '2022-01-01 15:00:00.000', sort: 'event_date', // genre_id: 3, // country_code: 'US', // min_resource_version: null, exclude_parking_passes: true }, }), ); console.log(response); return response.data?._embedded?.items; } catch (responseError) { console.error(`StubhubService: searchEventsByQuery() error: ${JSON.stringify(responseError)}`); this.updateAccessToken(); } } public async getEventById(eventId: number): Promise<any> { if (this.isAccessTokenExpired()) { this.updateAccessToken(); } try { const response = await firstValueFrom( this.httpService.get( `https://api.viagogo.net/catalog/events/${eventId}`, { headers: { Authorization: `Bearer ${this.accessToken}`, }, }, ), ); console.log(response.data); return response.data; } catch (err) { console.error(err); this.updateAccessToken(); } } private isAccessTokenExpired() { if(Date.now().valueOf() / 1000 > this.lastUpdateTimeStampOfAccessToken + this.timeStampExpiresIn) { return true; } return false; } }