Edits history of script submission #17671 for ' Get Job Codes [Batch] (paylocity)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Paylocity = {
    	clientId: string
    	clientSecret: string
    }
    /**
     * Get Job Codes [Batch]
     * **Summary Description**
    
    The GET Job Code List by Company ID endpoint, retrieves a comprehensive list of Job Codes from the Paylocity system with each call.
     */
    export async function main(
    	auth: Paylocity,
    	companyId: string,
    	filter: string | undefined,
    	limit: string | undefined,
    	offset: string | undefined,
    	testMode?: string
    ) {
    	const url = new URL(
    		`https://dc1prodgwext.paylocity.com/apiHub/payroll/v1/companies/${companyId}/jobs`
    	)
    	for (const [k, v] of [
    		['filter', filter],
    		['limit', limit],
    		['offset', offset]
    	]) {
    		if (v !== undefined && v !== '' && k !== undefined) {
    			url.searchParams.append(k, v)
    		}
    	}
    	const response = await fetch(url, {
    		method: 'GET',
    		headers: {
    			...(testMode ? { testMode: testMode } : {}),
    			Authorization:
    				'Bearer ' +
    				(await getOAuthToken(auth, 'https://dc1prodgwext.paylocity.com/public/security/v1/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: Paylocity, 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