Edits history of script submission #17734 for ' Get Custom Report by ID (personio)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Personio = {
    	clientId: string
    	clientSecret: string
    }
    /**
     * Get Custom Report by ID
     * This endpoint provides you with the data of an existing Custom Report.
     */
    export async function main(
    	auth: Personio,
    	report_id: string,
    	locale: string | undefined,
    	page: string | undefined,
    	limit: string | undefined,
    	X_Personio_Partner_ID?: string,
    	X_Personio_App_ID?: string
    ) {
    	const url = new URL(`https://api.personio.de/v1/company/custom-reports/reports/${report_id}`)
    	for (const [k, v] of [
    		['locale', locale],
    		['page', page],
    		['limit', limit]
    	]) {
    		if (v !== undefined && v !== '' && k !== undefined) {
    			url.searchParams.append(k, v)
    		}
    	}
    	const response = await fetch(url, {
    		method: 'GET',
    		headers: {
    			...(X_Personio_Partner_ID ? { 'X-Personio-Partner-ID': X_Personio_Partner_ID } : {}),
    			...(X_Personio_App_ID ? { 'X-Personio-App-ID': X_Personio_App_ID } : {}),
    			Authorization: 'Bearer ' + (await getOAuthToken(auth, 'https://api.personio.de/oauth2/token'))
    		},
    		body: undefined
    	})
    	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