refactor cache key calculation to have more space for dealing with different types of bodies

This commit is contained in:
Randall Schmidt 2020-11-28 11:17:25 -05:00
parent a7fc94c3e9
commit 8a338f5f5d

@ -1,5 +1,6 @@
const fetch = require('node-fetch');
const fs = require('fs');
const { URLSearchParams } = require('url');
const crypto = require('crypto');
const path = require('path');
@ -9,6 +10,29 @@ function md5(str) {
return crypto.createHash('md5').update(str).digest('hex');
}
function getBodyCacheKeyJson(body) {
if (typeof body === 'string') {
return body;
} if (body instanceof URLSearchParams) {
return body.toString();
}
return body;
}
function getCacheKey(requestArguments) {
const resource = requestArguments[0];
const init = requestArguments[1] || {};
const resourceCacheKeyJson = typeof resource === 'string' ? { url: resource } : { ...resource };
const initCacheKeyJson = { ...init };
resourceCacheKeyJson.body = getBodyCacheKeyJson(resourceCacheKeyJson.body);
initCacheKeyJson.body = getBodyCacheKeyJson(initCacheKeyJson.body);
return md5(JSON.stringify([resourceCacheKeyJson, initCacheKeyJson]));
}
async function createRawResponse(fetchRes) {
const buffer = await fetchRes.buffer();
@ -28,13 +52,8 @@ async function createRawResponse(fetchRes) {
}
async function getResponse(cacheDirPath, requestArguments) {
const [url, requestInit, ...rest] = requestArguments;
const requestParams = requestInit.body
? ({ ...requestInit, body: typeof requestInit.body === 'object' ? requestInit.body.toString() : requestInit.body })
: requestInit;
const cacheHash = md5(JSON.stringify([url, requestParams, ...rest]));
const cachedFilePath = path.join(cacheDirPath, `${cacheHash}.json`);
const cacheKey = getCacheKey(requestArguments);
const cachedFilePath = path.join(cacheDirPath, `${cacheKey}.json`);
try {
const rawResponse = JSON.parse(await fs.promises.readFile(cachedFilePath));