2021-08-12 15:04:37 +02:00
|
|
|
import Mustache from 'mustache';
|
|
|
|
import Addon from './addon';
|
|
|
|
import definition from './webhook-definition';
|
|
|
|
import { LogProvider } from '../logger';
|
2021-11-12 13:15:51 +01:00
|
|
|
import { IEvent } from '../types/events';
|
|
|
|
|
|
|
|
interface IParameters {
|
|
|
|
url: string;
|
|
|
|
bodyTemplate?: string;
|
|
|
|
contentType?: string;
|
|
|
|
}
|
2021-08-12 15:04:37 +02:00
|
|
|
|
|
|
|
export default class Webhook extends Addon {
|
|
|
|
constructor(args: { getLogger: LogProvider }) {
|
2021-01-19 10:42:45 +01:00
|
|
|
super(definition, args);
|
|
|
|
}
|
|
|
|
|
2021-11-12 13:15:51 +01:00
|
|
|
async handleEvent(event: IEvent, parameters: IParameters): Promise<void> {
|
2021-01-19 10:42:45 +01:00
|
|
|
const { url, bodyTemplate, contentType } = parameters;
|
|
|
|
const context = {
|
|
|
|
event,
|
|
|
|
};
|
|
|
|
|
|
|
|
let body;
|
|
|
|
|
|
|
|
if (typeof bodyTemplate === 'string' && bodyTemplate.length > 1) {
|
|
|
|
body = Mustache.render(bodyTemplate, context);
|
|
|
|
} else {
|
|
|
|
body = JSON.stringify(event);
|
|
|
|
}
|
|
|
|
|
|
|
|
const requestOpts = {
|
|
|
|
method: 'POST',
|
|
|
|
headers: { 'Content-Type': contentType || 'application/json' },
|
|
|
|
body,
|
|
|
|
};
|
|
|
|
const res = await this.fetchRetry(url, requestOpts);
|
|
|
|
|
|
|
|
this.logger.info(
|
|
|
|
`Handled event "${event.type}". Status code: ${res.status}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|