Edits history of script submission #22433 for ' Create Deal (hubspot)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import { Client } from "@hubspot/api-client@^8.1.0";
    
    /**
     * @param closedate Uses the following date-time format:
     * `2019-12-07T16:50:06.678Z` but time value can be omitted.
     */
    type Hubspot = {
      token: string;
    };
    export async function main(
      auth: Hubspot,
      amount?: string,
      closedate?: string,
      dealname?: string,
      dealstage?: string,
      hubspot_owner_id?: string,
      pipeline?: string,
    ) {
      const client = new Client({
        accessToken: auth.token,
      });
      const properties = removeObjectEmptyFields({
        amount,
        closedate,
        dealname,
        dealstage,
        hubspot_owner_id,
        pipeline,
      });
      try {
        return await client.crm.deals.basicApi.create({ properties });
      } catch (e) {
        throw Error(`
          ${e.code} - ${e.body.category}\n
          Message: ${e.body.message}\n
          Correlation ID: ${e.body.correlationId}
        `);
      }
    }
    
    function removeObjectEmptyFields(
      object?: Record<string, any>,
      removeEmptyArraysAndObjects = true,
      createNewObject = true,
    ) {
      if (!object || typeof object !== "object") return {}
      const obj = createNewObject ? { ...object } : object
      const emptyValues = [undefined, null, ""]
      for (const key in obj) {
        const value = obj[key]
        if (emptyValues.includes(value)) {
          delete obj[key]
        } else if (typeof value === "object") {
          if (Object.keys(value).length) {
            obj[key] = removeObjectEmptyFields(value, removeEmptyArraysAndObjects, false)
          }
          if (!Object.keys(value).length && removeEmptyArraysAndObjects) {
            delete obj[key]
          }
        }
      }
      return obj
    }
    

    Submitted by hugo989 4 days ago