Edits history of script submission #17772 for ' Update document metadata. (personio)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Personio = {
    	clientId: string
    	clientSecret: string
    }
    /**
     * Update document metadata.
     * Updates the metadata of the Document with the provided Document ID.
     */
    export async function main(
    	auth: Personio,
    	document_id: string,
    	body: {
    		id?: string
    		name?: string
    		date?: string
    		comment?: string
    		category?: { id?: string }
    		owner?: { id?: string }
    		document_type?: string
    		size?: number
    		created_at?: string
    		virus_scan?: { status?: 'unknown' | 'safe' | 'unsafe' }
    		esignature?: {
    			status?:
    				| 'status_unspecified'
    				| 'pending'
    				| 'signed'
    				| 'declined'
    				| 'canceled'
    				| 'expired'
    				| 'failed'
    				| 'email_bounced'
    		}
    	} & { owner?: { id?: {} } }
    ) {
    	const url = new URL(`https://api.personio.de/v2/document-management/documents/${document_id}`)
    
    	const response = await fetch(url, {
    		method: 'PATCH',
    		headers: {
    			'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.text()
    }
    
    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