Skip to content

Commit

Permalink
Add params to cache key
Browse files Browse the repository at this point in the history
Fix #85
  • Loading branch information
marcusolsson committed Apr 11, 2021
1 parent 94aa6f8 commit 7124c85
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export default class Api {
paramsData[key] = value;
});

const response = await this._request(method, path, paramsData, headers, body);
const response = this._request(method, path, paramsData, headers, body);

return (await response.toPromise()).data;
}
Expand Down Expand Up @@ -70,23 +70,28 @@ export default class Api {
return await this.get(method, path, params, headers, body);
}

const rawUrl = this.baseUrl + path;
let cacheKey = this.baseUrl + path;

const force = this.lastCacheDuration !== cacheDurationSeconds;
if (params && Object.keys(params).length > 0) {
cacheKey =
cacheKey +
(cacheKey.search(/\?/) >= 0 ? '&' : '?') +
params.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
}

if (force) {
this.cache.del(rawUrl);
if (this.lastCacheDuration !== cacheDurationSeconds) {
this.cache.del(cacheKey);
}
this.lastCacheDuration = cacheDurationSeconds;

const cachedItem = this.cache.get(rawUrl);
if (cachedItem && !force) {
const cachedItem = this.cache.get(cacheKey);
if (cachedItem) {
return Promise.resolve(cachedItem);
}
this.lastCacheDuration = cacheDurationSeconds;

const result = await this.get(method, path, params, headers, body);

this.cache.put(rawUrl, result, cacheDurationSeconds * 1000);
this.cache.put(cacheKey, result, cacheDurationSeconds * 1000);

return result;
}
Expand Down

0 comments on commit 7124c85

Please sign in to comment.