1 | |
2 | type Personio = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * Update a Person. |
8 | * - This endpoint enables the update of a Person resource. |
9 | - The endpoint requires the personio:persons:write scope. |
10 |
|
11 | */ |
12 | export async function main( |
13 | auth: Personio, |
14 | person_id: string, |
15 | body: { |
16 | email?: string |
17 | first_name?: string |
18 | preferred_name?: string |
19 | last_name?: string |
20 | gender?: 'MALE' | 'FEMALE' | 'DIVERSE' | 'UNKNOWN' | 'UNDEFINED' |
21 | language_code?: 'en' | 'de' | 'es' | 'fr' | 'nl' | 'it' | 'sv' | 'fi' |
22 | custom_attributes?: { id?: string; value?: string | string[] }[] |
23 | } |
24 | ) { |
25 | const url = new URL(`https://api.personio.de/v2/persons/${person_id}`) |
26 |
|
27 | const response = await fetch(url, { |
28 | method: 'PATCH', |
29 | headers: { |
30 | 'Content-Type': 'application/json', |
31 | Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token')) |
32 | }, |
33 | body: JSON.stringify(body) |
34 | }) |
35 | if (!response.ok) { |
36 | const text = await response.text() |
37 | throw new Error(`${response.status} ${text}`) |
38 | } |
39 | return await response.text() |
40 | } |
41 |
|
42 | async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> { |
43 | const params = new URLSearchParams({ |
44 | grant_type: 'client_credentials', |
45 | client_id: auth.clientId, |
46 | client_secret: auth.clientSecret |
47 | }) |
48 |
|
49 | const response = await fetch(tokenUrl, { |
50 | method: 'POST', |
51 | headers: { |
52 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
53 | 'Content-Type': 'application/x-www-form-urlencoded' |
54 | }, |
55 | body: params.toString() |
56 | }) |
57 |
|
58 | if (!response.ok) { |
59 | const text = await response.text() |
60 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
61 | } |
62 |
|
63 | const data = await response.json() |
64 | return data.access_token |
65 | } |
66 | } |
67 |
|