0
Create Request
One script reply has been approved by the moderators Verified

Creates a request. See docs here

Created by hugo697 200 days ago Viewed 3234 times
0
Submitted by hugo697 Bun
Verified 200 days ago
1
type Accelo = {
2
	clientId: string
3
	clientSecret: string
4
	deployment: string
5
}
6

7
export async function main(
8
	resource: Accelo,
9
	data: {
10
		title: string
11
		body: string
12
		type_id: number
13
		priority_id?: number
14
		source?: string
15
		leadId?: number
16
	} & (
17
		| { affiliation_id: number }
18
		| {
19
				affiliation: {
20
					contact?: {
21
						firstname: string
22
						lastname: string
23
					}
24
					company?: {
25
						name: string
26
						phone: string
27
					}
28
					email?: string
29
					phone?: string
30
				}
31
		  }
32
	)
33
) {
34
	// Fetch the access token
35
	const accessTokenResponse = (await (
36
		await fetch(`https://${resource.deployment}.api.accelo.com/oauth2/v0/token`, {
37
			method: 'POST',
38
			headers: {
39
				'Content-Type': 'application/x-www-form-urlencoded',
40
				Authorization: `Basic ${Buffer.from(
41
					`${resource.clientId}:${resource.clientSecret}`
42
				).toString('base64')}`
43
			},
44
			body: new URLSearchParams({
45
				grant_type: 'client_credentials',
46
				scope: 'write(all)'
47
			})
48
		})
49
	).json()) as any
50
	const accessToken = accessTokenResponse.access_token
51

52
	const form = new URLSearchParams()
53
	form.append('title', data.title)
54
	form.append('body', data.body)
55
	form.append('type_id', data.type_id.toString())
56
	data.priority_id && form.append('priority_id', data.priority_id.toString())
57
	data.source && form.append('source', data.source)
58
	data.leadId && form.append('lead_id', data.leadId.toString())
59
	if ('affiliation_id' in data) {
60
		form.append('affiliation_id', data.affiliation_id.toString())
61
	} else {
62
		if (data.affiliation.contact) {
63
			form.append('affiliation_contact_firstname', data.affiliation.contact.firstname)
64
			form.append('affiliation_contact_lastname', data.affiliation.contact.lastname)
65
		} else if (data.affiliation.company) {
66
			form.append('affiliation_company_name', data.affiliation.company.name)
67
			form.append('affiliation_company_phone', data.affiliation.company.phone)
68
		} else {
69
			form.append('affiliation_email', data.affiliation.email!)
70
			form.append('affiliation_phone', data.affiliation.phone!)
71
		}
72
	}
73

74
	return (
75
		await fetch(`https://${resource.deployment}.api.accelo.com/api/v0/requests`, {
76
			method: 'POST',
77
			headers: {
78
				'Content-Type': 'application/x-www-form-urlencoded',
79
				Authorization: `Bearer ${accessToken}`
80
			},
81
			body: form
82
		})
83
	).json()
84
}
85