@allgemein/http
Version:
Library for http request backend abstraction.
98 lines • 2.65 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpFactory = void 0;
const HttpGotAdapter_1 = require("../../adapters/http/got/HttpGotAdapter");
const lodash_1 = require("lodash");
class HttpFactory {
constructor() {
this.adapters = {};
}
/**
* Method to create singleton for this class
*/
static $() {
if (!this.__self__) {
this.__self__ = new HttpFactory();
}
return this.__self__;
}
/**
* Initialize factory and default got adapter (if installed)
*/
static load() {
if (!this.__loaded__) {
this.CLASSES.forEach(c => {
this.$().register(c);
});
this.__loaded__ = true;
}
return this.$();
}
/**
* Init factory and create an http adapter
*
* @param name
*/
static create(name = null) {
return this.load().create(name);
}
/**
* Register http adapter classes, the first added adapter will be the default at startup.
*
* @param clazz
*/
register(clazz) {
const adapter = Reflect.construct(clazz, []);
if (adapter) {
if (!(0, lodash_1.has)(this.adapters, adapter.name) && adapter.isAvailable()) {
if (Object.keys(this.adapters).length === 0) {
this.defaultAdapter = adapter.name;
}
this.adapters[adapter.name] = clazz;
return true;
}
}
return false;
}
/**
* Set default adapter name
*
* @param name
*/
setDefault(name) {
if ((0, lodash_1.has)(this.adapters, name)) {
this.defaultAdapter = name;
return true;
}
return false;
}
/**
* Get default adapter name
*/
getDefault() {
return this.defaultAdapter;
}
/**
* Get an existing http adapter
*
* @param name
*/
create(name = null) {
if (!name) {
name = this.defaultAdapter;
}
if (!name) {
throw new Error('http factory: no default adapter defined. ' + Object.keys(this.adapters));
}
if ((0, lodash_1.has)(this.adapters, name)) {
return Reflect.construct(this.adapters[name], []);
}
else {
throw new Error('http factory: no adapter with "' + name + '" defined.');
}
}
}
exports.HttpFactory = HttpFactory;
HttpFactory.CLASSES = [HttpGotAdapter_1.HttpGotAdapter];
HttpFactory.__loaded__ = false;
//# sourceMappingURL=HttpFactory.js.map