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