0

Create Contact

by
Published Jun 6, 2022
Script hubspot Verified

The script

Submitted by hugo989 Bun
Verified 13 days ago
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

Other submissions
  • Submitted by adam186 Deno
    Created 405 days ago
    1
    import { removeObjectEmptyFields } from "https://deno.land/x/[email protected]/mod.ts";
    2
    import { Client } from "npm:@hubspot/api-client@^8.1.0";
    3
    
    
    4
    type Hubspot = {
    5
      token: string;
    6
    };
    7
    export async function main(
    8
      auth: Hubspot,
    9
      company?: string,
    10
      email?: string,
    11
      firstname?: string,
    12
      lastname?: string,
    13
      phone?: string,
    14
      website?: string,
    15
    ) {
    16
      const client = new Client({
    17
        accessToken: auth.token,
    18
      });
    19
      const properties = removeObjectEmptyFields({
    20
        company,
    21
        email,
    22
        firstname,
    23
        lastname,
    24
        phone,
    25
        website,
    26
      });
    27
      try {
    28
        return await client.crm.contacts.basicApi.create({ properties });
    29
      } catch (e) {
    30
        throw Error(`
    31
          ${e.code} - ${e.body.category}\n
    32
          Message: ${e.body.message}\n
    33
          Correlation ID: ${e.body.correlationId}
    34
        `);
    35
      }
    36
    }
    37