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;
|
2022-11-09 11:45:30 +01:00
|
|
|
authorization?: string;
|
2023-07-05 09:42:17 +02:00
|
|
|
customHeaders?: string;
|
2021-11-12 13:15:51 +01:00
|
|
|
}
|
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> {
|
2023-07-05 09:42:17 +02:00
|
|
|
const { url, bodyTemplate, contentType, authorization, customHeaders } =
|
|
|
|
parameters;
|
2021-01-19 10:42:45 +01:00
|
|
|
const context = {
|
|
|
|
event,
|
|
|
|
};
|
|
|
|
|
|
|
|
let body;
|
|
|
|
|
|
|
|
if (typeof bodyTemplate === 'string' && bodyTemplate.length > 1) {
|
|
|
|
body = Mustache.render(bodyTemplate, context);
|
|
|
|
} else {
|
|
|
|
body = JSON.stringify(event);
|
|
|
|
}
|
|
|
|
|
2023-07-05 09:42:17 +02:00
|
|
|
let extraHeaders = {};
|
|
|
|
if (typeof customHeaders === 'string' && customHeaders.length > 1) {
|
|
|
|
try {
|
|
|
|
extraHeaders = JSON.parse(customHeaders);
|
|
|
|
} catch (e) {
|
|
|
|
this.logger.warn(
|
|
|
|
`Could not parse the json in the customHeaders parameter. [${customHeaders}]`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2021-01-19 10:42:45 +01:00
|
|
|
const requestOpts = {
|
|
|
|
method: 'POST',
|
2022-11-09 11:45:30 +01:00
|
|
|
headers: {
|
|
|
|
'Content-Type': contentType || 'application/json',
|
|
|
|
Authorization: authorization || undefined,
|
2023-07-05 09:42:17 +02:00
|
|
|
...extraHeaders,
|
2022-11-09 11:45:30 +01:00
|
|
|
},
|
2021-01-19 10:42:45 +01:00
|
|
|
body,
|
|
|
|
};
|
|
|
|
const res = await this.fetchRetry(url, requestOpts);
|
|
|
|
|
|
|
|
this.logger.info(
|
|
|
|
`Handled event "${event.type}". Status code: ${res.status}`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|