1 | |
2 | type Personio = { |
3 | clientId: string |
4 | clientSecret: string |
5 | } |
6 | |
7 | * Update Project by ID |
8 | * Updates a project with the given data |
9 | */ |
10 | export async function main( |
11 | auth: Personio, |
12 | id: string, |
13 | body: { name?: string; active?: false | true } |
14 | ) { |
15 | const url = new URL(`https://api.personio.de/v1/company/attendances/projects/${id}`) |
16 |
|
17 | const response = await fetch(url, { |
18 | method: 'PATCH', |
19 | headers: { |
20 | 'Content-Type': 'application/json', |
21 | Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token')) |
22 | }, |
23 | body: JSON.stringify(body) |
24 | }) |
25 | if (!response.ok) { |
26 | const text = await response.text() |
27 | throw new Error(`${response.status} ${text}`) |
28 | } |
29 | return await response.json() |
30 | } |
31 |
|
32 | async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> { |
33 | const params = new URLSearchParams({ |
34 | grant_type: 'client_credentials', |
35 | client_id: auth.clientId, |
36 | client_secret: auth.clientSecret |
37 | }) |
38 |
|
39 | const response = await fetch(tokenUrl, { |
40 | method: 'POST', |
41 | headers: { |
42 | Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`), |
43 | 'Content-Type': 'application/x-www-form-urlencoded' |
44 | }, |
45 | body: params.toString() |
46 | }) |
47 |
|
48 | if (!response.ok) { |
49 | const text = await response.text() |
50 | throw new Error(`OAuth token request failed: ${response.status} ${text}`) |
51 | } |
52 |
|
53 | const data = await response.json() |
54 | return data.access_token |
55 | } |
56 |
|