1 | |
2 | type Personio = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * Retrieves an Org Unit. |
8 | * - Returns the requested Org Unit. |
9 | - Supports enriching the response by providing options via query params, e.g. include_ancestors. |
10 | */ |
11 | export async function main( |
12 | auth: Personio, |
13 | id: string, |
14 | _type: string | undefined, |
15 | include_parent_chain: string | undefined |
16 | ) { |
17 | const url = new URL(`https://api.personio.de/v2/org-units/${id}`) |
18 | for (const [k, v] of [ |
19 | ['type', _type], |
20 | ['include_parent_chain', include_parent_chain] |
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 | Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token')) |
30 | }, |
31 | body: undefined |
32 | }) |
33 | if (!response.ok) { |
34 | const text = await response.text() |
35 | throw new Error(`${response.status} ${text}`) |
36 | } |
37 | return await response.json() |
38 | } |
39 |
|
40 | async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> { |
41 | const params = new URLSearchParams({ |
42 | grant_type: 'client_credentials', |
43 | client_id: auth.clientId, |
44 | client_secret: auth.clientSecret |
45 | }) |
46 |
|
47 | const response = await fetch(tokenUrl, { |
48 | method: 'POST', |
49 | headers: { |
50 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
51 | 'Content-Type': 'application/x-www-form-urlencoded' |
52 | }, |
53 | body: params.toString() |
54 | }) |
55 |
|
56 | if (!response.ok) { |
57 | const text = await response.text() |
58 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
59 | } |
60 |
|
61 | const data = await response.json() |
62 | return data.access_token |
63 | } |
64 |
|