diff --git a/src/Request.ts b/src/Request.ts index bb75926..95ed48c 100644 --- a/src/Request.ts +++ b/src/Request.ts @@ -1,60 +1,30 @@ -// Temporary disable this as it will be rebuilt to make it like the php-sdk one -// eslint-disable-next-line max-classes-per-file import TCGdex from './tcgdex' -export class Request { +export default class Request { // 1 hour of TTL by default public static ttl = 1000 * 60 * 60 - private response?: T + private static cache: Record = {} - private fetched?: Date - - public constructor( - // url is public for quick url test - public url: string - ) {} - - public async get(): Promise { - const now = new Date() - // if reponse was already fetched and TTL was not passed - if ( - this.fetched && - this.response && - now.getTime() - this.fetched.getTime() < Request.ttl - ) { - return this.response - } - - // Fetch Response - const unfetch = TCGdex.fetch - const resp = await unfetch(this.url, { - headers: { - 'user-agent': `@tcgdex/javascript-sdk/${TCGdex.VERSION}` + public static async fetch(url: string): Promise { + let request = this.cache[url] + const now = new Date().getTime() + if (!request || now - request.time > this.ttl) { + const unfetch = TCGdex.fetch + const resp = await unfetch(url, { + headers: { + 'user-agent': `@tcgdex/javascript-sdk/${TCGdex.VERSION}` + } + }) + if (resp.status !== 200) { + return undefined } - }) - if (resp.status !== 200) { - return undefined + + this.cache[url] = { response: await resp.json(), time: now } + request = this.cache[url] } - this.response = await resp.json() - this.fetched = now - return this.response - } - -} - -export default class RequestWrapper { - - private static cache: Array> = [] - - public static getRequest(url: string): Request { - let request = this.cache.find((req) => req.url === url) as Request|undefined - if (!request) { - request = new Request(url) - this.cache.push(request) - } - return request + return request.response } } diff --git a/src/tcgdex.ts b/src/tcgdex.ts index 515379a..e958d9d 100644 --- a/src/tcgdex.ts +++ b/src/tcgdex.ts @@ -179,7 +179,7 @@ export default class TCGdex { // eslint-disable-next-line no-misleading-character-class .replace(/["'\u0300-\u036f]/gu, '') )).join('/') - return RequestWrapper.getRequest(`${BASE_URL}/${this.getLang()}/${path}`).get() + return RequestWrapper.fetch(`${BASE_URL}/${this.getLang()}/${path}`) } }