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