import * as AWS from 'aws-sdk'; import {IResponse, response} from './tools'; AWS.config.update({region: 'us-east-1'}); // Virginia const SES = new AWS.SES(); //{apiVersion: '2010-12-01'} const SNS = new AWS.SNS(); export interface INotify { htmlContent?: string; textContent: string; from?: string; replyTo?: Array; emailAddresses?: Array; subject: string; phoneNumber?: string; values: any; // values to parse } function parseValues(content: string, values: any): string { const keys = Object.keys(values); for(let i = 0; i < keys.length; i++) { const reg = new RegExp('{{' + keys[i] + '}}', 'g'); content = content.toString().replace(reg, values[keys[i]]); } return content; } export class Notify { /** * * @param {INotify} body * @returns {Promise<>} */ async sendEmail(body: INotify): Promise { // Create sendEmail params let params = { Destination: { CcAddresses: [], ToAddresses: body.emailAddresses }, Message: { Body: { Html: { Charset: 'UTF-8', Data: body.values ? parseValues(body.htmlContent, body.values) : body.htmlContent }, Text: { Charset: 'UTF-8', Data: body.values ? parseValues(body.textContent, body.values) : body.textContent } }, Subject: { Charset: 'UTF-8', Data: body.values ? parseValues(body.subject, body.values) : body.subject } }, Source: body.from, ReplyToAddresses: body.replyTo }; try { const data = await SES.sendEmail(params).promise(); params['messageId'] = data; return response(true, null, params); } catch (error) { console.log(60, error); return response(false, error.message); } } /** * * @param {INotify} body * @returns {Promise<>} */ async sendSms(body: INotify): Promise { const params = { Message: body.values ? parseValues(body.textContent, body.values) : body.textContent, PhoneNumber: body.phoneNumber, Subject: body.values ? parseValues(body.subject, body.values) : body.subject }; try { const data = await SNS.publish(params).promise(); params['messageId'] = data; return response(true, null, params); } catch (error) { console.log(77, error); return response(false, error.message); } } }