libresilient/plugins/error/index.js

82 wiersze
2.5 KiB
JavaScript

/* ========================================================================= *\
|* === Error plugin === *|
\* ========================================================================= */
/**
* this plugin is just a debugging plugin to be used in testing configurations
* when an erroring-out plugin is needed
*/
// no polluting of the global namespace please
(function(LRPC){
// this never changes
const pluginName = "error"
LRPC.set(pluginName, (LR, init={})=>{
/*
* plugin config settings
*/
// sane defaults
let defaultConfig = {
// type can be "exception" or "http"
type: "http",
// only valid if type: http
code: 500,
// valid only if type: http
headers: {},
// valid either way
message: "Internal server error"
}
// merge the defaults with settings from init
let config = {...defaultConfig, ...init}
/**
* getting content using regular HTTP(S) fetch()
*/
let errorOut = (url, init={}) => {
// exception?
if (config.type !== "http") {
LR.log(pluginName, `erroring out for: ${url} — exception`)
throw new Error(config.message)
}
LR.log(pluginName, `erroring out for: ${url} — HTTP error`)
// I guess we want a HTTP error then
var responseInit = {
status: config.code,
statusText: config.message,
headers: config.headers,
url: url
};
// we need some content type here
if (responseInit.headers['Content-Type'] === undefined) {
responseInit.headers['Content-Type'] = "text/plain"
}
let blob = new Blob(
[config.message],
{type: "text/plain"}
)
// shouldn't this be a Promise though?
return Promise.resolve(new Response(
blob,
responseInit
))
}
// return the plugin
return {
name: pluginName,
description: 'Errors, errors everywhere',
version: 'COMMIT_UNKNOWN',
fetch: errorOut
}
})
// done with not polluting the global namespace
})(LibResilientPluginConstructors)