/
index.ts
73 lines (60 loc) · 1.76 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
import axios from "axios";
import nodemailer = require("nodemailer");
import Mail = require("nodemailer/lib/mailer");
class Api2Mailer {
public transporter: any;
public endpoint: string = 'http://localhost:2222';
public useNodemailer: boolean = false;
/**
* Create Transport
* @param transporter
* @param endpoint
*/
static createTransport(transporter: any, endpoint?: string) {
const api2Mailer = new this;
api2Mailer.transporter = transporter;
if (endpoint) api2Mailer.setEndpoint(endpoint);
return api2Mailer;
}
/**
* Use local nodemailer instead of api.
*/
useNodemailerInstead() {
this.transporter = nodemailer.createTransport(this.transporter)
this.useNodemailer = true;
return this;
}
/**
* Set Api's Endpoint
* @param endpoint
*/
setEndpoint(endpoint: string) {
this.endpoint = endpoint;
return this;
}
/**
* Send mail
* @param mail
* @param otherConfig
*/
async sendMail(mail: Mail.Options, otherConfig?: { background: boolean }) {
if (this.useNodemailer) {
return (this.transporter as Mail).sendMail(mail);
} else {
try {
let data: Record<string, any> = {mail, transporter: this.transporter};
if (otherConfig) {
data = {...data, ...otherConfig};
}
const response = await axios.post(this.endpoint, data);
if (response) {
const {data} = response;
return data.info;
}
} catch (err) {
throw Error(err.message)
}
}
}
}
export = Api2Mailer;