0

Get Freshdesk Contacts

by
Published Aug 26, 2024

Select one and provide the value.

Script freshdesk Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 652 days ago
1
type Freshdesk = {
2
	apiKey: string
3
	baseUrl: string
4
}
5

6
export async function main(
7
	resource: Freshdesk,
8
	filterType?: 'email' | 'mobile' | 'phone' | 'company_id' | 'updated_since',
9
	filterValue?: string,
10
	filterStatus?: 'blocked' | 'deleted' | 'unverified' | 'verified',
11
	perPage: number = 0
12
) {
13
	const baseUrl = resource.baseUrl.replace(/\/$/, '') // Remove trailing slash from base URL.
14
	const encodedKey = btoa(`${resource.apiKey}:X`) // Base64 encode the API key with a colon and 'X'.
15

16
	// Validate filterValue if filterType is provided
17
	if (filterType && !filterValue) {
18
		throw new Error('filterValue must be provided if filterType is specified.')
19
	}
20

21
	// Construct the query parameters.
22
	const queryParams = new URLSearchParams()
23
	if (filterType && filterValue) {
24
		queryParams.append(filterType, filterValue)
25
	}
26
	if (filterStatus) {
27
		queryParams.append('state', filterStatus)
28
	}
29
	if (perPage > 0) {
30
		queryParams.append('per_page', perPage.toString())
31
	}
32

33
	const endpoint = `${baseUrl}/api/v2/contacts?${queryParams.toString()}`
34

35
	const response = await fetch(endpoint, {
36
		method: 'GET',
37
		headers: {
38
			Authorization: `Basic ${encodedKey}`,
39
			'Content-Type': 'application/json'
40
		}
41
	})
42

43
	if (!response.ok) {
44
		console.log(response)
45
		throw new Error(`HTTP error! status: ${response.status}`)
46
	}
47

48
	const data = await response.json()
49
	return data
50
}
51