Add or Update Contact ( sendgrid)
One script reply has been approved by the moderators Verified

Created by sebastienyohlelo 296 days ago Viewed 52 times 0 Points

No comments yet

Login to be able to comment
Points: 0
deno
One script reply has been approved by the moderators
Ap­pro­ved
import * as wmill from "https://deno.land/x/windmill@v1.70.1/mod.ts"
import { removeObjectEmptyFields } from "https://deno.land/x/windmill_helpers@v1.0.0/mod.ts"
import sendgrid from "npm:@sendgrid/client@^7.7.0"

/**
 * According to Sendgrid documentation, this is an asynchronous 
 * process and the response will NOT contain immediate feedback, 
 * only a `job_id` which then can be used to get the status 
 * of the job.
 * The following script from WindmillHub performs this status check: 
 * https://hub.windmill.dev/scripts/sendgrid/1449/get-contacts-import-status-sendgrid
 * 
 * You can read more of the Sendgrid documentation at
 * https://docs.sendgrid.com/api-reference/contacts/add-or-update-a-contact
 */
export async function main(
  api_token: wmill.Resource<"sendgrid">,
  contacts: {
    email: string,
    custom_fields: Record<string, string | number>
  }[],
  list_ids?: string[],
) {
  sendgrid.setApiKey(api_token.token)

  try {
    contacts = contacts.map(c => {
      return typeof c === 'string' ? JSON.parse(c) : c
    })
  } catch(error) {
    throw Error(`Tried to parse "contacts" argument because 
    it was an array of strings but failed with error:\n${error}`)
  }

  const body = removeObjectEmptyFields({
    contacts,
    list_ids
  })
  const request = {
    url: `/v3/marketing/contacts`,
    method: 'PUT',
    body
  }

  try {
    const [_, body] = await sendgrid.request(request)
    return body
  } catch (error) {
    throw Error('\n' + (JSON.stringify(error?.response?.body || error)))
  }
}

Submitted by adam186 117 days ago

Edited 29 days ago

No comments yet

Login to be able to comment