1 | |
2 | type Personio = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * List attendance periods. |
8 | * List attendance periods by given filters. |
9 | */ |
10 | export async function main( |
11 | auth: Personio, |
12 | cursor: string | undefined, |
13 | limit: string | undefined, |
14 | id: string | undefined, |
15 | person_id: string | undefined, |
16 | start_date_time_gte: string | undefined, |
17 | start_date_time_lte: string | undefined, |
18 | end_date_time_lte: string | undefined, |
19 | end_date_time_gte: string | undefined, |
20 | updated_at_gte: string | undefined, |
21 | updated_at_lte: string | undefined, |
22 | status: 'PENDING' | 'CONFIRMED' | 'REJECTED' | undefined, |
23 | Beta: string |
24 | ) { |
25 | const url = new URL(`https://api.personio.de/v2/attendance-periods`) |
26 | for (const [k, v] of [ |
27 | ['cursor', cursor], |
28 | ['limit', limit], |
29 | ['id', id], |
30 | ['person.id', person_id], |
31 | ['start.date_time.gte', start_date_time_gte], |
32 | ['start.date_time.lte', start_date_time_lte], |
33 | ['end.date_time.lte', end_date_time_lte], |
34 | ['end.date_time.gte', end_date_time_gte], |
35 | ['updated_at.gte', updated_at_gte], |
36 | ['updated_at.lte', updated_at_lte], |
37 | ['status', status] |
38 | ]) { |
39 | if (v !== undefined && v !== '' && k !== undefined) { |
40 | url.searchParams.append(k, v) |
41 | } |
42 | } |
43 | const response = await fetch(url, { |
44 | method: 'GET', |
45 | headers: { |
46 | Beta: Beta, |
47 | Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token')) |
48 | }, |
49 | body: undefined |
50 | }) |
51 | if (!response.ok) { |
52 | const text = await response.text() |
53 | throw new Error(`${response.status} ${text}`) |
54 | } |
55 | return await response.json() |
56 | } |
57 |
|
58 | async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> { |
59 | const params = new URLSearchParams({ |
60 | grant_type: 'client_credentials', |
61 | client_id: auth.clientId, |
62 | client_secret: auth.clientSecret |
63 | }) |
64 |
|
65 | const response = await fetch(tokenUrl, { |
66 | method: 'POST', |
67 | headers: { |
68 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
69 | 'Content-Type': 'application/x-www-form-urlencoded' |
70 | }, |
71 | body: params.toString() |
72 | }) |
73 |
|
74 | if (!response.ok) { |
75 | const text = await response.text() |
76 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
77 | } |
78 |
|
79 | const data = await response.json() |
80 | return data.access_token |
81 | } |
82 |
|