Create a repository webhook

Repositories can have multiple webhooks installed. Each webhook should have a unique `config`. Multiple webhooks can share the same `config` as long as those webhooks do not have any `events` that overlap.

Script github Verified

by hugo697 ยท 10/25/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 366 days ago
1
type Github = {
2
  token: string;
3
};
4
/**
5
 * Create a repository webhook
6
 * Repositories can have multiple webhooks installed. Each webhook should have a unique `config`. Multiple webhooks can
7
share the same `config` as long as those webhooks do not have any `events` that overlap.
8
 */
9
export async function main(
10
  auth: Github,
11
  owner: string,
12
  repo: string,
13
  body: {
14
    active?: boolean;
15
    config?: {
16
      content_type?: string;
17
      digest?: string;
18
      insecure_ssl?: string | number;
19
      secret?: string;
20
      token?: string;
21
      url?: string;
22
      [k: string]: unknown;
23
    };
24
    events?: string[];
25
    name?: string;
26
  }
27
) {
28
  const url = new URL(`https://api.github.com/repos/${owner}/${repo}/hooks`);
29

30
  const response = await fetch(url, {
31
    method: "POST",
32
    headers: {
33
      "Content-Type": "application/json",
34
      Authorization: "Bearer " + auth.token,
35
    },
36
    body: JSON.stringify(body),
37
  });
38
  if (!response.ok) {
39
    const text = await response.text();
40
    throw new Error(`${response.status} ${text}`);
41
  }
42
  return await response.json();
43
}
44