1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-02-09 00:18:00 +01:00
unleash.unleash/src/lib/addons/datadog.ts
Christopher Kolstad 53354224fc
chore: Bump biome and configure husky (#6589)
Upgrades biome to 1.6.1, and updates husky pre-commit hook.

Most changes here are making type imports explicit.
2024-03-18 13:58:05 +01:00

97 lines
2.7 KiB
TypeScript

import Addon from './addon';
import definition from './datadog-definition';
import Mustache from 'mustache';
import type { IAddonConfig } from '../types/model';
import {
type FeatureEventFormatter,
FeatureEventFormatterMd,
LinkStyle,
} from './feature-event-formatter-md';
import type { IEvent } from '../types/events';
interface IDatadogParameters {
url: string;
apiKey: string;
sourceTypeName?: string;
customHeaders?: string;
bodyTemplate?: string;
}
interface DDRequestBody {
text: string;
title: string;
tags?: string[];
source_type_name?: string;
}
export default class DatadogAddon extends Addon {
private msgFormatter: FeatureEventFormatter;
constructor(config: IAddonConfig) {
super(definition, config);
this.msgFormatter = new FeatureEventFormatterMd(
config.unleashUrl,
LinkStyle.MD,
);
}
async handleEvent(
event: IEvent,
parameters: IDatadogParameters,
): Promise<void> {
const {
url = 'https://api.datadoghq.com/api/v1/events',
apiKey,
sourceTypeName,
customHeaders,
bodyTemplate,
} = parameters;
const context = {
event,
};
let text: string;
if (typeof bodyTemplate === 'string' && bodyTemplate.length > 1) {
text = Mustache.render(bodyTemplate, context);
} else {
text = `%%% \n ${this.msgFormatter.format(event).text} \n %%% `;
}
const { tags: eventTags } = event;
const tags = eventTags?.map((tag) => `${tag.type}:${tag.value}`);
const body: DDRequestBody = {
text: text,
title: 'Unleash notification update',
tags,
};
if (sourceTypeName) {
body.source_type_name = sourceTypeName;
}
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}]`,
);
}
}
const requestOpts = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'DD-API-KEY': apiKey,
...extraHeaders,
},
body: JSON.stringify(body),
};
const res = await this.fetchRetry(url, requestOpts);
this.logger.info(
`Handled event ${event.type}. Status codes=${res.status}`,
);
}
}