Edits history of script submission #17722 for ' Creates a new absence period. (personio)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Personio = {
    	clientId: string
    	clientSecret: string
    }
    /**
     * Creates a new absence period.
     * Creates a new absence period.
     */
    export async function main(
    	auth: Personio,
    	skip_approval: string | undefined,
    	Beta: string,
    	body: {
    		person: { id: string }
    		starts_from: { date_time: string; type?: 'FIRST_HALF' | 'SECOND_HALF' }
    		ends_at?: { date_time: string; type?: 'FIRST_HALF' | 'SECOND_HALF' }
    		comment?: string
    		absence_type: { id: string }
    	}
    ) {
    	const url = new URL(`https://api.personio.de/v2/absence-periods`)
    	for (const [k, v] of [['skip_approval', skip_approval]]) {
    		if (v !== undefined && v !== '' && k !== undefined) {
    			url.searchParams.append(k, v)
    		}
    	}
    	const response = await fetch(url, {
    		method: 'POST',
    		headers: {
    			Beta: Beta,
    			'Content-Type': 'application/json',
    			Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token'))
    		},
    		body: JSON.stringify(body)
    	})
    	if (!response.ok) {
    		const text = await response.text()
    		throw new Error(`${response.status} ${text}`)
    	}
    	return await response.json()
    }
    
    async function getOAuthToken(auth: Personio, tokenUrl: string): Promise<string> {
    	const params = new URLSearchParams({
    		grant_type: 'client_credentials',
    		client_id: auth.clientId,
    		client_secret: auth.clientSecret
    	})
    
    	const response = await fetch(tokenUrl, {
    		method: 'POST',
    		headers: {
    			Authorization: 'Basic ' + btoa(`${auth.clientId}:${auth.clientSecret}`),
    			'Content-Type': 'application/x-www-form-urlencoded'
    		},
    		body: params.toString()
    	})
    
    	if (!response.ok) {
    		const text = await response.text()
    		throw new Error(`OAuth token request failed: ${response.status} ${text}`)
    	}
    
    	const data = await response.json()
    	return data.access_token
    }
    

    Submitted by hugo697 235 days ago