Create private singleton class for Client

This commit is contained in:
Tee
2021-02-27 23:06:15 -05:00
parent e588d35dd9
commit 537a236b42

View File

@ -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<any> {
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<T>(resource: string, params?: Query[] | string): Promise<T> {
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<any>(url, config)
return axios.default.get<T>(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) {