UNPKG

2.85 kBPlain TextView Raw
1import * as AWS from 'aws-sdk';
2import {IResponse, response} from './tools';
3
4AWS.config.update({region: 'us-east-1'}); // Virginia
5
6const SES = new AWS.SES(); //{apiVersion: '2010-12-01'}
7const SNS = new AWS.SNS();
8
9export interface INotify {
10 htmlContent?: string;
11 textContent: string;
12 from?: string;
13 replyTo?: Array<string>;
14 emailAddresses?: Array<string>;
15 subject: string;
16 phoneNumber?: string;
17 values: any; // values to parse
18}
19
20function parseValues(content: string, values: any): string {
21 const keys = Object.keys(values);
22
23 for(let i = 0; i < keys.length; i++) {
24 const reg = new RegExp('{{' + keys[i] + '}}', 'g');
25 content = content.toString().replace(reg, values[keys[i]]);
26 }
27
28 return content;
29}
30
31export class Notify {
32
33 /**
34 *
35 * @param {INotify} body
36 * @returns {Promise<>}
37 */
38 async sendEmail(body: INotify): Promise<IResponse> {
39
40 // Create sendEmail params
41 let params = {
42 Destination: {
43 CcAddresses: [],
44 ToAddresses: body.emailAddresses
45 },
46 Message: {
47 Body: {
48 Html: {
49 Charset: 'UTF-8',
50 Data: body.values ? parseValues(body.htmlContent, body.values) : body.htmlContent
51 },
52 Text: {
53 Charset: 'UTF-8',
54 Data: body.values ? parseValues(body.textContent, body.values) : body.textContent
55 }
56 },
57 Subject: {
58 Charset: 'UTF-8',
59 Data: body.values ? parseValues(body.subject, body.values) : body.subject
60 }
61 },
62 Source: body.from,
63 ReplyToAddresses: body.replyTo
64 };
65
66 try {
67 const data = await SES.sendEmail(params).promise();
68 params['messageId'] = data;
69
70 return response(true, null, params);
71
72 } catch (error) {
73 console.log(60, error);
74 return response(false, error.message);
75 }
76 }
77
78 /**
79 *
80 * @param {INotify} body
81 * @returns {Promise<>}
82 */
83 async sendSms(body: INotify): Promise<IResponse> {
84 const params = {
85 Message: body.values ? parseValues(body.textContent, body.values) : body.textContent,
86 PhoneNumber: body.phoneNumber,
87 Subject: body.values ? parseValues(body.subject, body.values) : body.subject
88 };
89
90 try {
91 const data = await SNS.publish(params).promise();
92 params['messageId'] = data;
93
94 return response(true, null, params);
95 } catch (error) {
96 console.log(77, error);
97 return response(false, error.message);
98 }
99 }
100}
\No newline at end of file