forked from mailtrap/mailtrap-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheverything.ts
More file actions
57 lines (50 loc) · 1.45 KB
/
everything.ts
File metadata and controls
57 lines (50 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { MailtrapClient } from "mailtrap";
const TOKEN = "<YOUR-TOKEN-HERE>";
const ACCOUNT_ID = "<YOUR-ACCOUNT-ID-HERE>";
const client = new MailtrapClient({
token: TOKEN,
accountId: ACCOUNT_ID,
});
async function createContactEvent() {
try {
const email = `john.smith+${Date.now()}@example.com`;
let contactId: string;
// Try to get existing contact first
try {
const existing = await client.contacts.get(email);
contactId = existing.data.id;
} catch (_getErr) {
// Not found, create minimal contact
try {
const created = await client.contacts.create({ email });
contactId = created.data.id;
} catch (err: any) {
const cause = err?.cause || err;
const status = cause?.response?.status;
if (status === 409) {
const existing = await client.contacts.get(email);
contactId = existing.data.id;
} else {
throw err;
}
}
}
const payload = {
name: "purchase_completed",
params: {
order_id: 12345,
amount: 49.99,
currency: "USD",
coupon_used: false,
},
};
const event = await client.contactEvents.create(contactId, payload);
console.log("Contact event created:", JSON.stringify(event, null, 2));
} catch (error) {
console.error(
"Error creating contact event:",
error instanceof Error ? error.message : String(error)
);
}
}
createContactEvent();