1 | |
2 |
|
3 | type Datadog = { |
4 | apiKey: string; |
5 | appKey: string; |
6 | apiBase: string; |
7 | }; |
8 |
|
9 | |
10 | * Find Monitors |
11 | * Search for monitors and return every match (following pagination). Leave |
12 | * `query` empty to return all monitors, or pass a Datadog monitor search |
13 | * query such as `type:metric` or `env:production`. |
14 | */ |
15 | export async function main(dd_auth: Datadog, query: string = "") { |
16 | const monitors = []; |
17 | for await (const monitor of searchToEnd(dd_auth, query)) { |
18 | monitors.push(monitor); |
19 | } |
20 | return monitors; |
21 | } |
22 |
|
23 | async function* searchToEnd(dd_auth: Datadog, query: string) { |
24 | let page = 0; |
25 | let pageCount = 1; |
26 | while (page < pageCount) { |
27 | const url = new URL(`${dd_auth.apiBase}/api/v1/monitor/search`); |
28 | if (query !== "") { |
29 | url.searchParams.append("query", query); |
30 | } |
31 | url.searchParams.append("page", String(page)); |
32 |
|
33 | const response = await fetch(url, { |
34 | method: "GET", |
35 | headers: { |
36 | "DD-API-KEY": dd_auth.apiKey, |
37 | "DD-APPLICATION-KEY": dd_auth.appKey, |
38 | Accept: "application/json", |
39 | }, |
40 | }); |
41 |
|
42 | if (!response.ok) { |
43 | throw new Error(`${response.status} ${await response.text()}`); |
44 | } |
45 |
|
46 | const result = await response.json(); |
47 | for (const monitor of result.monitors ?? []) { |
48 | yield monitor; |
49 | } |
50 | pageCount = result.metadata?.page_count ?? 1; |
51 | page++; |
52 | } |
53 | } |
54 |
|