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