0

Batch Create Associations

by
Published today

Associate many pairs of CRM records in one call.

Script hubspot Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours ago
1
//native
2

3
export type DynSelect_object_type = string
4

5
// Dropdown of the standard CRM object types plus the account's custom objects.
6
export async function object_type(auth: RT.Hubspot) {
7
  const standard = [
8
    "contacts",
9
    "companies",
10
    "deals",
11
    "tickets",
12
    "line_items",
13
    "products",
14
    "quotes",
15
    "leads",
16
    "notes",
17
    "tasks",
18
    "meetings",
19
    "calls",
20
    "emails",
21
    "communications",
22
  ].map((o) => ({ value: o, label: o }))
23
  const response = await fetch("https://api.hubapi.com/crm/v3/schemas", {
24
    headers: {
25
      Authorization: `Bearer ${auth.token}`,
26
      Accept: "application/json",
27
    },
28
  })
29
  // A token without crm.schemas.custom.read still gets the standard objects.
30
  if (!response.ok) return standard
31
  const { results } = (await response.json()) as {
32
    results: { fullyQualifiedName: string; labels: { plural: string } }[]
33
  }
34
  return [
35
    ...standard,
36
    ...results.map((s) => ({
37
      value: s.fullyQualifiedName,
38
      label: `${s.labels.plural} (custom)`,
39
    })),
40
  ]
41
}
42

43
/**
44
 * Batch Create Associations
45
 * Associate many pairs of CRM records in one call. Each input holds `from.id`, `to.id` and the association `types` (see List Association Labels). Object types other than contacts, companies and deals need their own scope on the connection (e.g. tickets, crm.objects.line_items.read, crm.objects.custom.read).
46
 */
47
export async function main(
48
  auth: RT.Hubspot,
49
  from_object_type: DynSelect_object_type,
50
  to_object_type: DynSelect_object_type,
51
  inputs: {
52
    from: { id: string }
53
    to: { id: string }
54
    types: { associationCategory: string; associationTypeId: number }[]
55
  }[]
56
) {
57
  const url = new URL(
58
    `https://api.hubapi.com/crm/v4/associations/${from_object_type}/${to_object_type}/batch/create`
59
  )
60

61
  const body: { [key: string]: any } = {}
62
  body.inputs = inputs
63

64
  const response = await fetch(url, {
65
    method: "POST",
66
    headers: {
67
      Authorization: `Bearer ${auth.token}`,
68
      "Content-Type": "application/json",
69
      Accept: "application/json",
70
    },
71
    body: JSON.stringify(body),
72
  })
73

74
  if (!response.ok) {
75
    throw new Error(`${response.status} ${await response.text()}`)
76
  }
77
  if (response.status === 204) return { success: true }
78

79
  return await response.json()
80
}
81