|
|
@ -46,45 +46,46 @@ class Onionoo { |
|
|
|
let url = `${this.options.baseUrl}/${endpoint}`; |
|
|
|
url += qs ? `?${qs}` : ''; |
|
|
|
|
|
|
|
// If caching is disabled, just make the request
|
|
|
|
if (!this.options.cache) { |
|
|
|
return this.makeRequest(url); |
|
|
|
} |
|
|
|
|
|
|
|
// If caching is enabled, check for url in cache
|
|
|
|
if (this.options.cache) { |
|
|
|
return this.options.cache.get(url) |
|
|
|
.then(cachedResult => { |
|
|
|
let options = {}; |
|
|
|
|
|
|
|
// If we have it cached
|
|
|
|
if (cachedResult) { |
|
|
|
// Return the cached entry if it's still valid
|
|
|
|
if (!expired(cachedResult.headers)) { |
|
|
|
return cachedResult; |
|
|
|
|
|
|
|
// If it's stale, add last-modified date to headers
|
|
|
|
} else if (cachedResult.headers['last-modified']) { |
|
|
|
options.headers = { |
|
|
|
'if-modified-since': cachedResult.headers['last-modified'] |
|
|
|
}; |
|
|
|
} |
|
|
|
return this.options.cache.get(url) |
|
|
|
.then(cachedResult => { |
|
|
|
let options = {}; |
|
|
|
|
|
|
|
// If we have it cached
|
|
|
|
if (cachedResult) { |
|
|
|
// Return the cached entry if it's still valid
|
|
|
|
if (!expired(cachedResult.headers)) { |
|
|
|
return cachedResult; |
|
|
|
|
|
|
|
// If it's stale, add last-modified date to headers
|
|
|
|
} else if (cachedResult.headers['last-modified']) { |
|
|
|
options.headers = { |
|
|
|
'if-modified-since': cachedResult.headers['last-modified'] |
|
|
|
}; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// Make a request
|
|
|
|
return this.makeRequest(url, options) |
|
|
|
.then(response => { |
|
|
|
// If we get a 304, fill in the body
|
|
|
|
if (response.statusCode === 304) { |
|
|
|
response.body = cachedResult.body; |
|
|
|
} |
|
|
|
|
|
|
|
// Make a request
|
|
|
|
return this.makeRequest(url, options) |
|
|
|
.then(response => { |
|
|
|
// If we get a 304, fill in the body
|
|
|
|
if (response.statusCode === 304) { |
|
|
|
response.body = cachedResult.body; |
|
|
|
} |
|
|
|
|
|
|
|
// If we get a 200 or 304, cache it
|
|
|
|
if ([200, 304].includes(response.statusCode)) { |
|
|
|
this.options.cache.set(url, response); |
|
|
|
} |
|
|
|
|
|
|
|
return response; |
|
|
|
}); |
|
|
|
}); |
|
|
|
} |
|
|
|
// If caching is disabled, just make the request
|
|
|
|
return this.makeRequest(url); |
|
|
|
// If we get a 200 or 304, cache it
|
|
|
|
if ([200, 304].includes(response.statusCode)) { |
|
|
|
this.options.cache.set(url, response); |
|
|
|
} |
|
|
|
|
|
|
|
return response; |
|
|
|
}); |
|
|
|
}); |
|
|
|
}; |
|
|
|
} |
|
|
|
|
|
|
|