1 | |
2 |
|
3 | |
4 | * List job templates |
5 | * List one page of job templates visible to the credential. Returns the API's page envelope: count, next and previous page URLs, and results. Pass page + 1 to fetch the next page while next is not null. |
6 | */ |
7 | export async function main( |
8 | auth: RT.Awx, |
9 | page: number | undefined, |
10 | page_size: number | undefined, |
11 | search: string | undefined |
12 | ) { |
13 | const url = new URL(`${apiRoot(auth)}/job_templates/`) |
14 | if (page) { |
15 | url.searchParams.append("page", String(page)) |
16 | } |
17 | if (page_size != null) { |
18 | url.searchParams.append("page_size", String(page_size)) |
19 | } |
20 | if (search != null && search !== "") { |
21 | url.searchParams.append("search", search) |
22 | } |
23 |
|
24 | const response = await fetch(url, { |
25 | headers: { |
26 | Authorization: authorization(auth), |
27 | Accept: "application/json", |
28 | }, |
29 | }) |
30 |
|
31 | if (!response.ok) { |
32 | throw new Error(`${response.status} ${await response.text()}`) |
33 | } |
34 |
|
35 | return await response.json() |
36 | } |
37 |
|
38 | function apiRoot(auth: RT.Awx) { |
39 | const path = (auth.api_path || "/api/v2").replace(/^\/+|\/+$/g, "") |
40 | |
41 | const base = auth.base_url |
42 | .replace(/\/+$/, "") |
43 | .replace(new RegExp(`/${path}$`), "") |
44 | return `${base}/${path}` |
45 | } |
46 |
|
47 | function authorization(auth: RT.Awx) { |
48 | if (auth.token) { |
49 | return `Bearer ${auth.token}` |
50 | } |
51 | if (auth.username) { |
52 | const bytes = new TextEncoder().encode( |
53 | `${auth.username}:${auth.password ?? ""}` |
54 | ) |
55 | return `Basic ${btoa(String.fromCharCode(...bytes))}` |
56 | } |
57 | throw new Error( |
58 | "The AWX resource needs either a token or a username and password" |
59 | ) |
60 | } |
61 |
|