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