2021-08-12 15:04:37 +02:00
|
|
|
import fetch, { Response } from 'node-fetch';
|
|
|
|
import { addonDefinitionSchema } from './addon-schema';
|
|
|
|
import { IUnleashConfig } from '../types/option';
|
|
|
|
import { Logger } from '../logger';
|
|
|
|
import { IAddonDefinition, IEvent } from '../types/model';
|
2021-01-19 10:42:45 +01:00
|
|
|
|
2021-08-12 15:04:37 +02:00
|
|
|
export default abstract class Addon {
|
|
|
|
logger: Logger;
|
2021-01-19 10:42:45 +01:00
|
|
|
|
2021-08-12 15:04:37 +02:00
|
|
|
_name: string;
|
|
|
|
|
|
|
|
_definition: IAddonDefinition;
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
definition: IAddonDefinition,
|
|
|
|
{ getLogger }: Pick<IUnleashConfig, 'getLogger'>,
|
|
|
|
) {
|
2021-01-19 10:42:45 +01:00
|
|
|
this.logger = getLogger(`addon/${definition.name}`);
|
|
|
|
const { error } = addonDefinitionSchema.validate(definition);
|
|
|
|
if (error) {
|
|
|
|
this.logger.warn(
|
|
|
|
`Could not load addon provider ${definition.name}`,
|
|
|
|
error,
|
|
|
|
);
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
this._name = definition.name;
|
|
|
|
this._definition = definition;
|
|
|
|
}
|
|
|
|
|
2021-08-12 15:04:37 +02:00
|
|
|
get name(): string {
|
2021-01-19 10:42:45 +01:00
|
|
|
return this._name;
|
|
|
|
}
|
|
|
|
|
2021-08-12 15:04:37 +02:00
|
|
|
get definition(): IAddonDefinition {
|
2021-01-19 10:42:45 +01:00
|
|
|
return this._definition;
|
|
|
|
}
|
|
|
|
|
2021-08-12 15:04:37 +02:00
|
|
|
async fetchRetry(
|
|
|
|
url: string,
|
|
|
|
options = {},
|
|
|
|
retries: number = 1,
|
|
|
|
backoff: number = 300,
|
|
|
|
): Promise<Response> {
|
2021-01-19 10:42:45 +01:00
|
|
|
const retryCodes = [408, 500, 502, 503, 504, 522, 524];
|
2021-02-28 22:40:04 +01:00
|
|
|
let res;
|
2021-02-26 13:46:56 +01:00
|
|
|
try {
|
2021-02-28 22:40:04 +01:00
|
|
|
res = await fetch(url, options);
|
2021-02-26 13:46:56 +01:00
|
|
|
} catch (error) {
|
2021-02-28 22:40:04 +01:00
|
|
|
res = { status: 500, ok: false };
|
|
|
|
}
|
|
|
|
if (res.ok) {
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
if (retries > 0 && retryCodes.includes(res.status)) {
|
2021-04-16 15:29:23 +02:00
|
|
|
setTimeout(
|
|
|
|
() => this.fetchRetry(url, options, retries - 1, backoff * 2),
|
|
|
|
backoff,
|
|
|
|
);
|
2021-01-19 10:42:45 +01:00
|
|
|
}
|
2021-02-28 22:40:04 +01:00
|
|
|
return res;
|
2021-01-19 10:42:45 +01:00
|
|
|
}
|
|
|
|
|
2021-08-12 15:04:37 +02:00
|
|
|
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
|
|
|
abstract handleEvent(event: IEvent, parameters: any): Promise<void>;
|
|
|
|
}
|