-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
85 lines (64 loc) · 2.06 KB
/
index.ts
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { Config, Message } from "./types.ts";
export default class Mailgun {
private basic: string;
private endpoint: string;
constructor(config: Config) {
const base64 = btoa(`api:${config.key}`);
this.basic = `Basic ${base64}`;
this.endpoint =
typeof config.region !== "undefined" && config.region === "eu"
? `https://api.eu.mailgun.net/v3/${config.domain}/messages`
: `https://api.mailgun.net/v3/${config.domain}/messages`;
}
send(message: Message): Promise<Response> {
const form = new FormData();
// For package simplicity we'll parse the reply property into the correct header
if (message["reply"]) {
message["h:Reply-To"] = message.reply;
delete message["reply"];
}
for (const property in message) {
if (Object.prototype.hasOwnProperty.call(message, property)) {
const key = property as keyof Message;
const value = message[key];
this.mailgunStringify(key, value, form);
}
}
const method = "POST";
const headers = { Authorization: this.basic };
return fetch(this.endpoint, { method, headers, body: form });
}
private mailgunStringify(
key: keyof Message,
value: Message[keyof Message],
form: FormData,
): void {
// Return early if the value is undefined
if (value === undefined) {
return;
}
// Handle single file
if (value instanceof File) {
form.append(key, value);
return;
}
// Handle array of files
const isArray = Array.isArray(value);
const isFiles = isArray && value.every((item) => item instanceof File);
if (isFiles) {
value.forEach((file, index) => {
form.append(`${key}[${index}]`, file);
});
return;
}
// Handle array of strings
if (Array.isArray(value)) {
const parsedValue = value.join(",");
form.append(key, parsedValue);
return;
}
// For all other types (boolean, string), convert to string and append
const valueStringified = value.toString();
form.append(key, valueStringified);
}
}