1 | import { ApifyClient } from 'apify-client@^2.19.0'; |
2 |
|
3 | type ApifyApiKey = { |
4 | api_key: string; |
5 | }; |
6 |
|
7 | type Apify = { |
8 | token: string; |
9 | }; |
10 |
|
11 | type ApifyWebhookConfig = { |
12 | url: string; |
13 | token: string; |
14 | }; |
15 |
|
16 | function prettifyEvent(e: string) { |
17 | return e.replace(/^ACTOR\.RUN\./, ''); |
18 | } |
19 |
|
20 | const createClient = (api_key?: ApifyApiKey, oauth_token?: Apify): ApifyClient => { |
21 | const token = oauth_token?.token ?? api_key?.api_key; |
22 | if (!token) { |
23 | throw new Error('Missing Apify API key or OAuth token'); |
24 | } |
25 |
|
26 | return new ApifyClient({ |
27 | token: token, |
28 | requestInterceptors: [ |
29 | (request) => { |
30 | if (!request.headers) { |
31 | request.headers = {}; |
32 | } |
33 | request.headers['x-apify-integration-platform'] = 'windmill'; |
34 | return request; |
35 | }, |
36 | ], |
37 | }); |
38 | }; |
39 |
|
40 | export type DynSelect_webhookToDelete = string; |
41 | export async function webhookToDelete( |
42 | apifyWebhookConfig: ApifyWebhookConfig, |
43 | api_key?: ApifyApiKey, |
44 | oauth_token?: Apify, |
45 | ) { |
46 | if (!api_key?.api_key && !oauth_token?.token) { |
47 | return [{ value: '', label: 'Missing Apify API key or OAuth token' }]; |
48 | } |
49 |
|
50 | try { |
51 | const client = createClient(api_key, oauth_token); |
52 | const webhooks = await client.webhooks().list({ |
53 | limit: 1000, |
54 | offset: 0, |
55 | }); |
56 |
|
57 | return webhooks.items |
58 | .filter((webhook) => webhook.requestUrl === apifyWebhookConfig.url) |
59 | .map((webhook) => { |
60 | const webhookEvents = webhook.eventTypes |
61 | .map((event) => prettifyEvent(event)) |
62 | .join(', '); |
63 | const condition = webhook.condition as any; |
64 | const fallbackLabel = `${condition.actorId ?? condition.actorTaskId}: ${webhookEvents}`; |
65 | return { |
66 | value: webhook.id, |
67 | label: webhook?.description || fallbackLabel, |
68 | }; |
69 | }); |
70 | } catch (error: any) { |
71 | return [ |
72 | { |
73 | value: '', |
74 | label: `Failed to load webhooks: ${error.message || error}`, |
75 | }, |
76 | ]; |
77 | } |
78 | } |
79 |
|
80 | export async function main( |
81 | apifyWebhookConfig: ApifyWebhookConfig, |
82 | webhookToDelete: DynSelect_webhookToDelete, |
83 | api_key?: ApifyApiKey, |
84 | oauth_token?: Apify, |
85 | ) { |
86 | if (!webhookToDelete) { |
87 | return { error: 'Please select webhook ID for deletion.' }; |
88 | } |
89 |
|
90 | const client = createClient(api_key, oauth_token); |
91 |
|
92 | try { |
93 | await client.webhook(webhookToDelete).delete(); |
94 | return { success: 'Webhook deleted successfully' }; |
95 | } catch (e: any) { |
96 | return { error: `Failed to delete the webhook. Reason: ${e.message}` }; |
97 | } |
98 | } |
99 |
|