From 537a236b4238df460cd1b52b81902c7b581217ac Mon Sep 17 00:00:00 2001 From: Tee Date: Sat, 27 Feb 2021 23:06:15 -0500 Subject: [PATCH] Create private singleton class for Client --- src/client.ts | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/src/client.ts b/src/client.ts index 5f71332..bb79a43 100644 --- a/src/client.ts +++ b/src/client.ts @@ -2,29 +2,48 @@ import * as axios from 'axios'; import { Query } from './interfaces/query'; export class Client { - private static readonly API_BASE_URL: string = 'https://api.pokemontcg.io'; - private static readonly API_VERSION: string = '2'; - private static readonly API_URL: string = `${Client.API_BASE_URL}/v${Client.API_VERSION}`; + private readonly POKEMONTCG_API_BASE_URL: string = 'https://api.pokemontcg.io'; + private readonly POKEMONTCG_API_VERSION: string = '2'; + private readonly POKEMONTCG_API_URL: string = `${this.POKEMONTCG_API_BASE_URL}/v${this.POKEMONTCG_API_VERSION}`; + private readonly POKEMONTCG_API_KEY?: string = process.env.POKEMONTCG_API_KEY; - static async get(resource: string, params?: Query[] | string): Promise { - let url: string = `${this.API_URL}/${resource}`; - const config: axios.AxiosRequestConfig = { - headers: { - 'Content-Type': 'application/json' + private static instance: Client; + + private constructor() {} + + public static getInstance() { + if (!Client.instance) { + Client.instance = new Client(); } + + return Client.instance; + } + + async get(resource: string, params?: Query[] | string): Promise { + let url: string = `${this.POKEMONTCG_API_URL}/${resource}`; + let headers = { + 'Content-Type': 'application/json' + } + + if (this.POKEMONTCG_API_KEY) { + headers['X-Api-Key'] = this.POKEMONTCG_API_KEY; + } + + const config: axios.AxiosRequestConfig = { + headers }; if(typeof params === 'string') url += `/${params}`; else url += `?${this.paramsToQuery(params)}`; - return axios.default.get(url, config) + return axios.default.get(url, config) .then(response => { return response.data[Object.keys(response.data)[0]]; }) .catch(error => Promise.reject(error)); } - private static paramsToQuery(params?: Query[]): string { + private paramsToQuery(params?: Query[]): string { let query: string = ''; if (params) {