libresilient/plugins/fetch.js

80 wiersze
2.8 KiB
JavaScript
Czysty Zwykły widok Historia

2021-04-06 17:18:37 +00:00
/* ========================================================================= *\
|* === Regular HTTP(S) fetch() plugin === *|
\* ========================================================================= */
/**
* this plugin does not implement any push method
*/
// no polluting of the global namespace please
(function () {
/*
* plugin config settings
*/
// sane defaults
let defaultConfig = {
// name of this plugin
// should not be changed
name: "fetch"
}
// merge the defaults with settings from LibResilientConfig
let config = {...defaultConfig, ...self.LibResilientConfig.plugins[defaultConfig.name]}
/**
* getting content using regular HTTP(S) fetch()
*/
let fetchContent = (url) => {
self.log(config.name, `regular fetch: ${url}`)
return fetch(url, {cache: "reload"})
.then((response) => {
// 4xx? 5xx? that's a paddlin'
if (response.status >= 400) {
// throw an Error to fall back to LibResilient:
throw new Error('HTTP Error: ' + response.status + ' ' + response.statusText);
}
// all good, it seems
self.log(config.name, `fetched successfully: ${response.url}`);
// we need to create a new Response object
// with all the headers added explicitly,
// since response.headers is immutable
var init = {
status: response.status,
statusText: response.statusText,
headers: {},
url: response.url
2021-04-06 17:18:37 +00:00
};
response.headers.forEach(function(val, header){
init.headers[header] = val;
});
// add the X-LibResilient-* headers to the mix
init.headers['X-LibResilient-Method'] = config.name
init.headers['X-LibResilient-ETag'] = response.headers.get('ETag')
// return the new response, using the Blob from the original one
return response
.blob()
.then((blob) => {
return new Response(
blob,
init
)
})
})
}
// and add ourselves to it
// with some additional metadata
self.LibResilientPlugins.push({
name: config.name,
description: 'Just a regular HTTP(S) fetch()',
version: 'COMMIT_UNKNOWN',
fetch: fetchContent
})
// done with not poluting the global namespace
})()