1 | |
2 | type Personio = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * Get Employee Profile Picture |
8 | * Show employee's profile picture. If profile picture is missing, the 404 error will be thrown. The `Profile Picture` attribute has to be whitelisted. |
9 | */ |
10 | export async function main( |
11 | auth: Personio, |
12 | employee_id: string, |
13 | width: string, |
14 | X_Personio_Partner_ID?: string, |
15 | X_Personio_App_ID?: string |
16 | ) { |
17 | const url = new URL( |
18 | `https://api.personio.de/v1/company/employees/${employee_id}/profile-picture/${width}` |
19 | ) |
20 |
|
21 | const response = await fetch(url, { |
22 | method: 'GET', |
23 | headers: { |
24 | ...(X_Personio_Partner_ID ? { 'X-Personio-Partner-ID': X_Personio_Partner_ID } : {}), |
25 | ...(X_Personio_App_ID ? { 'X-Personio-App-ID': X_Personio_App_ID } : {}), |
26 | Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token')) |
27 | }, |
28 | body: undefined |
29 | }) |
30 | if (!response.ok) { |
31 | const text = await response.text() |
32 | throw new Error(`${response.status} ${text}`) |
33 | } |
34 | return await response.text() |
35 | } |
36 |
|
37 | async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> { |
38 | const params = new URLSearchParams({ |
39 | grant_type: 'client_credentials', |
40 | client_id: auth.clientId, |
41 | client_secret: auth.clientSecret |
42 | }) |
43 |
|
44 | const response = await fetch(tokenUrl, { |
45 | method: 'POST', |
46 | headers: { |
47 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
48 | 'Content-Type': 'application/x-www-form-urlencoded' |
49 | }, |
50 | body: params.toString() |
51 | }) |
52 |
|
53 | if (!response.ok) { |
54 | const text = await response.text() |
55 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
56 | } |
57 |
|
58 | const data = await response.json() |
59 | return data.access_token |
60 | } |
61 | } |
62 |
|