|
| 1 | +import {EnvironmentConfigService} from '../environment/environment-config.service'; |
| 2 | + |
| 3 | +import {get, set} from 'idb-keyval'; |
| 4 | + |
| 5 | +import {ErrorService} from '../error/error.service'; |
| 6 | + |
| 7 | +export class GifService { |
| 8 | + |
| 9 | + private static instance: GifService; |
| 10 | + |
| 11 | + private errorService: ErrorService; |
| 12 | + |
| 13 | + private constructor() { |
| 14 | + // Private constructor, singleton |
| 15 | + this.errorService = ErrorService.getInstance(); |
| 16 | + } |
| 17 | + |
| 18 | + static getInstance() { |
| 19 | + if (!GifService.instance) { |
| 20 | + GifService.instance = new GifService(); |
| 21 | + } |
| 22 | + return GifService.instance; |
| 23 | + } |
| 24 | + |
| 25 | + // call the trending and category endpoints |
| 26 | + getTrending(): Promise<TenorGif[]> { |
| 27 | + return new Promise<TenorGif[]>(async (resolve, reject) => { |
| 28 | + const apiKey: string = EnvironmentConfigService.getInstance().get('tenorKey'); |
| 29 | + const searchTerm: string = 'excited'; |
| 30 | + |
| 31 | + const anonymousId: string = await this.getAnonymousId(); |
| 32 | + |
| 33 | + const searchUrl = 'https://api.tenor.com/v1/search?tag=' + searchTerm + '&key=' + |
| 34 | + apiKey + '&ar_range=wide&limit=' + 8 + '&anon_id=' + anonymousId + '&media_filter=minimal'; |
| 35 | + |
| 36 | + try { |
| 37 | + const rawResponse: Response = await fetch(searchUrl); |
| 38 | + |
| 39 | + const response: TenorTrendingResponse = JSON.parse(await rawResponse.text()); |
| 40 | + |
| 41 | + if (!response) { |
| 42 | + reject('Tenor trending could not be fetched'); |
| 43 | + } |
| 44 | + |
| 45 | + resolve(response.results); |
| 46 | + } catch (err) { |
| 47 | + this.errorService.error(err.message); |
| 48 | + reject(err); |
| 49 | + } |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + private getAnonymousId(): Promise<string> { |
| 54 | + return new Promise<string>(async (resolve, reject) => { |
| 55 | + const localAnonymousId: string = await get('tenor_anonid'); |
| 56 | + |
| 57 | + if (localAnonymousId) { |
| 58 | + resolve(localAnonymousId); |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + const apiKey: string = EnvironmentConfigService.getInstance().get('tenorKey'); |
| 63 | + |
| 64 | + try { |
| 65 | + const rawResponse: Response = await fetch('https://api.tenor.com/v1/anonid?key=' + apiKey); |
| 66 | + |
| 67 | + const response: TenorAnonymousResponse = JSON.parse(await rawResponse.text()); |
| 68 | + |
| 69 | + if (!response) { |
| 70 | + reject('Tenor anonymous ID could not be fetched'); |
| 71 | + } |
| 72 | + |
| 73 | + const anonymousId: string = response.anon_id; |
| 74 | + |
| 75 | + await set('tenor_anonid', anonymousId); |
| 76 | + |
| 77 | + resolve(anonymousId); |
| 78 | + } catch (err) { |
| 79 | + reject(err); |
| 80 | + } |
| 81 | + }); |
| 82 | + } |
| 83 | +} |
0 commit comments