0
Add or Update Contact
One script reply has been approved by the moderators Verified
Created by sebastienyohlelo 681 days ago Viewed 4112 times
0
Submitted by adam186 Deno
Verified 503 days ago
1
import { removeObjectEmptyFields } from "https://deno.land/x/windmill_helpers@v1.0.0/mod.ts";
2
import sendgrid from "npm:@sendgrid/client@^7.7.0";
3

4
/**
5
 * According to Sendgrid documentation, this is an asynchronous
6
 * process and the response will NOT contain immediate feedback,
7
 * only a `job_id` which then can be used to get the status
8
 * of the job.
9
 * The following script from WindmillHub performs this status check:
10
 * https://hub.windmill.dev/scripts/sendgrid/1449/get-contacts-import-status-sendgrid
11
 *
12
 * You can read more of the Sendgrid documentation at
13
 * https://docs.sendgrid.com/api-reference/contacts/add-or-update-a-contact
14
 */
15
type Sendgrid = {
16
  token: string;
17
};
18
export async function main(
19
  api_token: Sendgrid,
20
  contacts: {
21
    email: string;
22
    custom_fields: Record<string, string | number>;
23
  }[],
24
  list_ids?: string[],
25
) {
26
  sendgrid.setApiKey(api_token.token);
27

28
  try {
29
    contacts = contacts.map((c) => {
30
      return typeof c === "string" ? JSON.parse(c) : c;
31
    });
32
  } catch (error) {
33
    throw Error(`Tried to parse "contacts" argument because 
34
    it was an array of strings but failed with error:\n${error}`);
35
  }
36

37
  const body = removeObjectEmptyFields({
38
    contacts,
39
    list_ids,
40
  });
41
  const request = {
42
    url: `/v3/marketing/contacts`,
43
    method: "PUT",
44
    body,
45
  };
46

47
  try {
48
    const [_, body] = await sendgrid.request(request);
49
    return body;
50
  } catch (error) {
51
    throw Error("\n" + JSON.stringify(error?.response?.body || error));
52
  }
53
}
54