Allow Client.get to accept a string for ID path parameter

This commit is contained in:
Ryan Munro (Monbrey)
2019-08-03 09:22:35 +10:00
parent 93535ff9ad
commit 682f90c49a
2 changed files with 20 additions and 43 deletions

View File

@ -5,7 +5,7 @@ import { IQuery } from './interfaces/query';
export class Client {
static apiUrl: string = `${PokemonTCG.API_URL}/v${PokemonTCG.version}`;
static get(resource: string, params?: IQuery[]): Promise<any> {
static get(resource: string, params?: IQuery[] | string): Promise<any> {
let url: string = `${this.apiUrl}/${resource}`;
let config: axios.AxiosRequestConfig = {
headers: {
@ -13,30 +13,15 @@ export class Client {
}
};
// This is needed because the /sets endpoint doesn't take
// an id as a parameter so we need to append it to the url
url += this.checkForId(resource, params);
if(typeof params === 'string') url += `/${params}`;
else url += `?${this.paramsToQuery(params)}`;
return axios.default.get<any>(`${url}?${this.paramsToQuery(params)}`, config)
return axios.default.get<any>(url, config)
.then(response => {
return response.data[Object.keys(response.data)[0]];
})
}
private static checkForId(resource: string, params?: IQuery[]): string {
let url: string = '';
if (params) {
params.map(param => {
if (param.name === 'id') {
url = `/${param.value}`;
}
});
}
return url;
}
private static paramsToQuery(params?: IQuery[]): string {
let query: string = '';

View File

@ -5,33 +5,25 @@ import { IQuery } from './interfaces/query';
import { AxiosResponse } from 'axios';
export class QueryBuilder {
static all<T extends Card | Set>(type: (new() => T)): Promise<T[]> {
let t = new type();
let params: IQuery[] = [{
name: 'pageSize',
value: 1000
}];
static all<T extends Card | Set>(type: (new () => T)): Promise<T[]> {
let t = new type();
let params: IQuery[] = [{
name: 'pageSize',
value: 1000
}];
return this.returnResponse(t.resource(), params);
}
return Client.get(t.resource(), params).catch(error => console.error(error));
}
static find<T extends Card | Set>(type: (new() => T), id: string): Promise<T> {
let t = new type();
let params: IQuery[] = [{
name: 'id',
value: id
}];
static find<T extends Card | Set>(type: (new () => T), id: string): Promise<T> {
let t = new type();
return this.returnResponse(t.resource(), params);
}
return Client.get(t.resource(), id).catch(error => console.error(error));
}
static where<T extends Card | Set>(type: (new() => T), params: IQuery[]): Promise<T[]> {
let t = new type();
static where<T extends Card | Set>(type: (new () => T), params: IQuery[]): Promise<T[]> {
let t = new type();
return this.returnResponse(t.resource(), params);
}
private static returnResponse(resource: string, params: IQuery[]): Promise<any> {
return Client.get(resource, params).catch(error => console.error(error));
}
return Client.get(t.resource(), params).catch(error => console.error(error));
}
}