import { Client } from "@hubspot/api-client@^8.1.0";
type Hubspot = {
token: string;
};
export async function main(
auth: Hubspot,
company?: string,
email?: string,
firstname?: string,
lastname?: string,
phone?: string,
website?: string,
) {
const client = new Client({
accessToken: auth.token,
});
const properties = removeObjectEmptyFields({
company,
email,
firstname,
lastname,
phone,
website,
});
try {
return await client.crm.contacts.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 13 days ago