-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
72 lines (59 loc) · 1.73 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import {
PluginInput,
Plugin,
Meta,
RetryError,
PluginEvent,
} from "@posthog/plugin-scaffold";
import fetch, { Response } from "node-fetch";
type PatternsInputs = {
webhookUrl: string;
allowedEventTypes: string;
};
export interface PatternsPluginInput extends PluginInput {
config: PatternsInputs;
}
const filterEvents = (
events: PluginEvent[],
config: PatternsInputs
): PluginEvent[] => {
if (!config.allowedEventTypes) {
return events;
}
let allowedEventTypes = config.allowedEventTypes.split(",");
allowedEventTypes = allowedEventTypes.map((eventType) => eventType.trim());
const allowedEventTypesSet = new Set(allowedEventTypes);
let filteredEvents = events.filter((event) =>
allowedEventTypesSet.has(event.event)
);
return filteredEvents;
};
// Plugin method that runs on plugin load
//@ts-ignore
export async function setupPlugin({ config }: Meta<PatternsPluginInput>) {
console.log("Loaded Patterns app.");
}
// Plugin method to export events
export const exportEvents: Plugin<PatternsPluginInput>["exportEvents"] = async (
events: PluginEvent[],
{ config }: Meta<PatternsPluginInput>
) => {
let filteredEvents = filterEvents(events, config);
console.log(
`Exporting events to Patterns webhook... ${filteredEvents.length}/${events.length} events`
);
if (!filteredEvents.length) {
return;
}
let response: Response;
response = await fetch(config.webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(filteredEvents),
});
if (response.status != 200) {
const data = await response.json();
throw new RetryError(`Export events failed: ${JSON.stringify(data)}`);
}
console.log("Export Success.");
};