0

Get All Tickets By Status

by
Published Aug 26, 2024

Get All Tickets by selected status from Freshdesk.

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
	status: 'Open' | 'Pending' | 'Resolved' | 'Closed'
9
) {
10
	// Map status to corresponding Freshdesk status code
11
	const statusMap: { [key: string]: number } = {
12
		Open: 2,
13
		Pending: 3,
14
		Resolved: 4,
15
		Closed: 5
16
	}
17

18
	// Get the corresponding status code
19
	const statusCode = statusMap[status]
20
	if (!statusCode) {
21
		throw new Error(`Invalid status: ${status}`)
22
	}
23

24
	// Remove the trailing slash from base URL.
25
	const baseUrl = resource.baseUrl.replace(/\/$/, '')
26

27
	// Base64 encode the API key with a colon and 'X'
28
	const encodedKey = btoa(`${resource.apiKey}:X`)
29

30
	// Construct the query parameter and encode it
31
	const query = encodeURIComponent(`"status:${statusCode}"`)
32

33
	const endpoint = `${baseUrl}/api/v2/search/tickets?query=${query}`
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
		throw new Error(`HTTP error! status: ${response.status}`)
45
	}
46

47
	const data = await response.json()
48

49
	return data.results
50
}
51