1 | |
2 | type Personio = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * List absence types. |
8 | * List absence type. |
9 | */ |
10 | export async function main( |
11 | auth: Personio, |
12 | cursor: string | undefined, |
13 | limit: string | undefined, |
14 | Beta: string |
15 | ) { |
16 | const url = new URL(`https://api.personio.de/v2/absence-types`) |
17 | for (const [k, v] of [ |
18 | ['cursor', cursor], |
19 | ['limit', limit] |
20 | ]) { |
21 | if (v !== undefined && v !== '' && k !== undefined) { |
22 | url.searchParams.append(k, v) |
23 | } |
24 | } |
25 | const response = await fetch(url, { |
26 | method: 'GET', |
27 | headers: { |
28 | Beta: Beta, |
29 | Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token')) |
30 | }, |
31 | body: undefined |
32 | }) |
33 | if (!response.ok) { |
34 | const text = await response.text() |
35 | throw new Error(`${response.status} ${text}`) |
36 | } |
37 | return await response.json() |
38 | } |
39 |
|
40 | async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> { |
41 | const params = new URLSearchParams({ |
42 | grant_type: 'client_credentials', |
43 | client_id: auth.clientId, |
44 | client_secret: auth.clientSecret |
45 | }) |
46 |
|
47 | const response = await fetch(tokenUrl, { |
48 | method: 'POST', |
49 | headers: { |
50 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
51 | 'Content-Type': 'application/x-www-form-urlencoded' |
52 | }, |
53 | body: params.toString() |
54 | }) |
55 |
|
56 | if (!response.ok) { |
57 | const text = await response.text() |
58 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
59 | } |
60 |
|
61 | const data = await response.json() |
62 | return data.access_token |
63 | } |
64 |
|