1 | import { Client } from "npm:@hubspot/api-client@^8.1.0"; |
2 | import type { AssociationSpec } from "npm:@hubspot/api-client@^8.1.0/lib/codegen/crm/contacts/index.js"; |
3 |
|
4 | type Hubspot = { |
5 | token: string; |
6 | }; |
7 | export async function main( |
8 | auth: Hubspot, |
9 | contact_id: number, |
10 | to_object_type: string, |
11 | to_object_id: number, |
12 | associations: AssociationSpec[], |
13 | ) { |
14 | const client = new Client({ |
15 | accessToken: auth.token, |
16 | }); |
17 |
|
18 | try { |
19 | associations = |
20 | associations?.map((c) => { |
21 | return typeof c === "string" ? JSON.parse(c) : c; |
22 | }) || []; |
23 | } catch (error) { |
24 | throw Error(`Tried to parse "associations" argument because |
25 | it was an array of strings but failed with error:\n${error} |
26 | Associations must have the following shape: |
27 | { |
28 | associationCategory: 'HUBSPOT_DEFINED' | 'USER_DEFINED' | 'INTEGRATOR_DEFINED', |
29 | associationTypeId: number |
30 | } |
31 | `); |
32 | } |
33 |
|
34 | try { |
35 | return await client.crm.contacts.associationsApi.create( |
36 | contact_id, |
37 | to_object_type, |
38 | to_object_id, |
39 | associations, |
40 | ); |
41 | } catch (e) { |
42 | throw Error(` |
43 | ${e.code}\n |
44 | Message: ${e.body.message || e.body}\n |
45 | `); |
46 | } |
47 | } |
48 |
|