1 | import { Client } from "@hubspot/api-client@^8.1.0"; |
2 |
|
3 | type Hubspot = { |
4 | token: string; |
5 | }; |
6 | export async function main( |
7 | auth: Hubspot, |
8 | company?: string, |
9 | email?: string, |
10 | firstname?: string, |
11 | lastname?: string, |
12 | phone?: string, |
13 | website?: string, |
14 | ) { |
15 | const client = new Client({ |
16 | accessToken: auth.token, |
17 | }); |
18 | const properties = removeObjectEmptyFields({ |
19 | company, |
20 | email, |
21 | firstname, |
22 | lastname, |
23 | phone, |
24 | website, |
25 | }); |
26 | try { |
27 | return await client.crm.contacts.basicApi.create({ properties }); |
28 | } catch (e) { |
29 | throw Error(` |
30 | ${e.code} - ${e.body.category}\n |
31 | Message: ${e.body.message}\n |
32 | Correlation ID: ${e.body.correlationId} |
33 | `); |
34 | } |
35 | } |
36 |
|
37 | function removeObjectEmptyFields( |
38 | object?: Record<string, any>, |
39 | removeEmptyArraysAndObjects = true, |
40 | createNewObject = true, |
41 | ) { |
42 | if (!object || typeof object !== "object") return {} |
43 | const obj = createNewObject ? { ...object } : object |
44 | const emptyValues = [undefined, null, ""] |
45 | for (const key in obj) { |
46 | const value = obj[key] |
47 | if (emptyValues.includes(value)) { |
48 | delete obj[key] |
49 | } else if (typeof value === "object") { |
50 | if (Object.keys(value).length) { |
51 | obj[key] = removeObjectEmptyFields(value, removeEmptyArraysAndObjects, false) |
52 | } |
53 | if (!Object.keys(value).length && removeEmptyArraysAndObjects) { |
54 | delete obj[key] |
55 | } |
56 | } |
57 | } |
58 | return obj |
59 | } |
60 |
|