Skip to content
22 changes: 20 additions & 2 deletions src/http-data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export type Request<T = unknown> = {
origin: string
path: string
method: HttpMethod
// Indicates if the response of this request should be memoized
memoize?: boolean
headers: Dictionary<string>
} & CacheTTLOptions

Expand Down Expand Up @@ -141,6 +143,16 @@ export abstract class HTTPDataSource<TContext = any> extends DataSource {
return statusCodeCacheableByDefault.has(response.statusCode) && request.method === 'GET'
}

/**
* Checks if the GET request is memoizable. This validation is performed before the
* response is set in **memoisedResults**.
* @param request
* @returns *true* if request should be memoized
*/
protected isRequestMemoizable(request: Request): boolean {
return Boolean(request.memoize)
}

/**
* onCacheKeyCalculation returns the key for the GET request.
* The key is used to memoize the request in the LRU cache.
Expand Down Expand Up @@ -193,6 +205,7 @@ export abstract class HTTPDataSource<TContext = any> extends DataSource {
headers: {},
query: {},
body: null,
memoize: true,
context: {},
...requestOptions,
method: 'GET',
Expand Down Expand Up @@ -390,15 +403,20 @@ export abstract class HTTPDataSource<TContext = any> extends DataSource {
return cachedResponse
}
const response = this.performRequest<TResult>(options, cacheKey)
this.memoizedResults.set(cacheKey, response)
if (this.isRequestMemoizable(request)) {
this.memoizedResults.set(cacheKey, response)
}

return response
} catch (error: any) {
this.logger?.error(`Cache item '${cacheKey}' could not be loaded: ${error.message}`)
}
}

const response = this.performRequest<TResult>(options, cacheKey)
this.memoizedResults.set(cacheKey, response)
if (this.isRequestMemoizable(request)) {
this.memoizedResults.set(cacheKey, response)
}

return response
}
Expand Down
Loading