0

Get Ticket Status

by
Published Aug 26, 2024

The Ticket ID to return status

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
type TicketStatus = 'Open' | 'Pending' | 'Resolved' | 'Closed'
7

8
export async function main(resource: Freshdesk, ticketId: string) {
9
	const statusMap: { [key: number]: TicketStatus } = {
10
		2: 'Open',
11
		3: 'Pending',
12
		4: 'Resolved',
13
		5: 'Closed'
14
	}
15

16
	// Remove the trailing slash from base URL
17
	const baseUrl = resource.baseUrl.replace(/\/$/, '')
18
	const url = `${baseUrl}/api/v2/tickets/${ticketId}`
19

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

23
	const response = await fetch(url, {
24
		method: 'GET',
25
		headers: {
26
			Authorization: `Basic ${encodedKey}`,
27
			'Content-Type': 'application/json'
28
		}
29
	})
30

31
	if (!response.ok) {
32
		throw new Error(`HTTP error! status: ${response.status}`)
33
	}
34

35
	const data = await response.json()
36

37
	const status = data.status
38
	const responderId = data.responder_id
39
	let assignedStatusFriendlyValue = ''
40
	let ticketStatusFriendlyValue: TicketStatus | number
41

42
	if (responderId == null) {
43
		assignedStatusFriendlyValue = 'NOTASSIGNED'
44
	} else {
45
		assignedStatusFriendlyValue = 'ASSIGNED'
46
	}
47

48
	ticketStatusFriendlyValue = statusMap[status] ?? status
49

50
	const result = {
51
		ticket_status: ticketStatusFriendlyValue,
52
		assigned_status: assignedStatusFriendlyValue,
53
		assigned_id: responderId
54
	}
55

56
	return result
57
}
58