From 75b85eb03e0d65bd9d9ce776154e6cc3d0ed3447 Mon Sep 17 00:00:00 2001 From: Rhys Arkins Date: Sat, 13 Jun 2020 06:30:09 +0200 Subject: [PATCH] refactor: http cache --- lib/util/http/index.ts | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/lib/util/http/index.ts b/lib/util/http/index.ts index bff118fdd9040d..f685aa47f06c22 100644 --- a/lib/util/http/index.ts +++ b/lib/util/http/index.ts @@ -1,6 +1,5 @@ import crypto from 'crypto'; import URL from 'url'; -import { GotPromise } from 'got'; import * as runCache from '../cache/run'; import { clone } from '../clone'; import got from '../got'; @@ -34,10 +33,7 @@ export interface HttpResponse { headers: any; } -async function cloneResponse( - promisedResponse: GotPromise -): Promise> { - const response = await promisedResponse; +function cloneResponse(response: any): HttpResponse { // clone body and headers so that the cached result doesn't get accidentally mutated return { body: clone(response.body), @@ -48,7 +44,7 @@ async function cloneResponse( export class Http { constructor(private hostType: string, private options?: HttpOptions) {} - protected request( + protected async request( requestUrl: string | URL, httpOptions?: InternalHttpOptions ): Promise | null> { @@ -94,24 +90,24 @@ export class Http { options = applyAuthorization(options); // Cache GET requests unless useCache=false - let promisedRes: GotPromise; - if (options.method === 'get') { - const cacheKey = crypto - .createHash('md5') - .update('got-' + JSON.stringify({ url, headers: options.headers })) - .digest('hex'); - if (options.useCache !== false) { - // check cache unless bypassing it - promisedRes = runCache.get(cacheKey); - } - if (promisedRes === undefined) { - // cache miss OR cache bypass - promisedRes = got(url, options); + const cacheKey = crypto + .createHash('md5') + .update('got-' + JSON.stringify({ url, headers: options.headers })) + .digest('hex'); + if (options.method === 'get' && options.useCache !== false) { + // return from cache if present + const cachedRes = runCache.get(cacheKey); + // istanbul ignore if + if (cachedRes) { + return cloneResponse(await cachedRes); } - runCache.set(cacheKey, promisedRes); // always set - return cloneResponse(promisedRes); } - return cloneResponse(got(url, options)); + const promisedRes = got(url, options); + if (options.method === 'get') { + runCache.set(cacheKey, promisedRes); // always set if it's a get + } + const res = await promisedRes; + return cloneResponse(res); } get(url: string, options: HttpOptions = {}): Promise {