Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update #1

Merged
merged 1 commit into from
Jun 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,19 @@
"author": "",
"license": "ISC",
"dependencies": {
"@google-cloud/pubsub": "^3.0.1",
"@types/nodemailer": "^6.4.4",
"axios": "^0.27.2",
"axios-cookiejar-support": "^4.0.2",
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"moment": "^2.29.3",
"nodemailer": "^6.7.5",
"redis": "^4.1.0",
"simple-gcp-logging": "git+https://github.com/HDRUK/simple-gcp-logging.git#main",
"tough-cookie": "^4.0.0",
"tslib": "^2.4.0",
"typescript": "^4.7.3"
},
Expand Down
37 changes: 37 additions & 0 deletions src/controllers/apikey.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const BaseController = require('./base.controller');

export default class ApiKeyController extends BaseController {
#url: string;
#body;
#options;
#bearer;

constructor() {
super();
this.#url = '';
this.#body = {};
this.#options = {};
this.#bearer = '';
}

setUrl(url: string) {
return this.#url = url;
}

setBody(body) {
return this.#body = body;
}

setOptions(options) {
return this.#options = options;
}

setBearer(bearer: string) {
return this.#bearer = bearer;
}

async sendPostRequest() {
return await this.postRequest(this.#url, this.#body, this.#options, this.#bearer);
}

}
22 changes: 22 additions & 0 deletions src/controllers/base.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// import { LoggingService } from '../services/google/LoggingService';
import { LoggingService, HttpClientCervice } from "../services";

class BaseController {
#logger;
#httpClient;

constructor(){
this.#logger = new LoggingService();
this.#httpClient = new HttpClientCervice();
}

sendLoggingMessage(message: string, type: string) {
return this.#logger.sendDataInLogging(message, type);
}

async postRequest(url, body, options, bearer) {
return await this.#httpClient.post(url, body, options, bearer);
}
}

module.exports = BaseController;
59 changes: 59 additions & 0 deletions src/controllers/mail.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import connectMail from "../services/mail.service";

import SMTPTransport = require('nodemailer/lib/smtp-transport');

const BaseController = require('./base.controller');

export default class MailController extends BaseController {
#transporter;
#fromEmail;
#toEmail;
#subjectEmail;
#textEmail;
#htmlEmail;

constructor() {
super();
this.#transporter = connectMail();
}

async sendEmail() {
const message = {
from: this.#fromEmail,
to: this.#toEmail,
subject: this.#subjectEmail,
text: this.#textEmail // Plain text body
};

return await this.#transporter.sendMail(message, (err, info: SMTPTransport.SentMessageInfo) => {
if (err) {
this.sendLoggingMessage(JSON.stringify(err), 'ERROR');
throw new Error(err.message);
}

this.sendLoggingMessage(JSON.stringify(info), 'INFO');

console.log('Message sent: %s', info.messageId);
});
}

setFromEmail(email: string) {
return this.#fromEmail = email;
}

setToEmail(email: string) {
return this.#toEmail = email;
}

setSubjectEmail(subjectEmail: string) {
return this.#subjectEmail = subjectEmail;
}

setTextEmail(textEmail: string) {
return this.#textEmail = textEmail;
}

setHtmlEmail(htmlEmail: string) {
return this.#htmlEmail = htmlEmail;
}
}
96 changes: 84 additions & 12 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,23 @@ import 'dotenv/config';
import express, { Request, Response } from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import { createClient } from 'redis';
import { LoggingService } from './services';
import moment from 'moment';
import { PubSub, Message } from '@google-cloud/pubsub';
import { LoggingService } from './services/index';

const app = express();
const logger = new LoggingService();

const PORT = process.env.PORT || 3005;
const HOST = process.env.HOST;
const cacheUrl = process.env.CACHE_URL || '';
const cacheChannel = process.env.CACHE_CHANNEL || '';
const HOST = process.env.HOST || '';
const pubSubProjectId = process.env.PUBSUB_PROJECT_ID || '';
const pubSubTopicEnquiry = process.env.PUBSUB_TOPIC_ENQUIRY || '';
const pubSubSubscriptionId = process.env.PUBSUB_SUBSCRIPTION_ID || '';

import MailController from './controllers/mail.controller';
import ApiKeyController from './controllers/apikey.controller';
const mailController = new MailController();
const apiKeyController = new ApiKeyController();

app.use(express.json());
app.use(cors());
Expand All @@ -26,17 +33,82 @@ app.get('/', (req: Request, res: Response) => {
});
});

(async () => {
const client = createClient({
url: cacheUrl,
{
const pubsub = new PubSub({
projectId: pubSubProjectId
});

await client.connect();
const subscription = pubsub.subscription(pubSubSubscriptionId);

// Create an event handler to handle messages
const messageHandler = async (message: Message) => {

const datetime = moment().format('mmmm do yyyy, hh:mm:ss a');
process.stdout.write(`\n----------------------------------------------------------------\n`);
const messageToJSON = JSON.parse(JSON.parse( message.data.toString()));

const typeOfMessage = messageToJSON.type;
const typeOfAuthentification = messageToJSON.darIntegration.outbound.auth.type;

let response;
if (typeOfAuthentification === 'api_key') {
const baseUrl = messageToJSON.darIntegration.outbound.endpoints.baseURL;
const endpoint = messageToJSON.darIntegration.outbound.endpoints[typeOfMessage];
const secretKey = messageToJSON.darIntegration.outbound.auth.secretKey;
apiKeyController.setUrl(`${baseUrl}${endpoint}`);
apiKeyController.setBearer(secretKey);
apiKeyController.setBody(messageToJSON.details);
response = await apiKeyController.sendPostRequest();
}

process.stdout.write(response.status);
process.stdout.write(`\tMessage deliveryAttempt: ${JSON.stringify(message.deliveryAttempt)}\n`);
if (response.status === 'error') {
mailController.setFromEmail('[email protected]');
mailController.setToEmail('[email protected]');
mailController.setSubjectEmail(`Response Status: ${response.status} - ${message.deliveryAttempt}`);
const textEmail = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis hendrerit leo, quis vestibulum dolor.';
mailController.setTextEmail(textEmail);
await mailController.sendEmail();

logger.sendDataInLogging(response, 'ERROR');

await client.subscribe(cacheChannel, (message) => {
logger.sendDataInLogging(message, 'INFO');
message.nack();
}

if (response.status === 'success') {
mailController.setFromEmail('[email protected]');
mailController.setToEmail('[email protected]');
mailController.setSubjectEmail(`Response Status: ${response.status} - ${message.deliveryAttempt}`);
const textEmail = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis hendrerit leo, quis vestibulum dolor.';
mailController.setTextEmail(textEmail);
await mailController.sendEmail();

logger.sendDataInLogging(response, 'INFO');

message.ack();
}

logger.sendDataInLogging(JSON.parse(message.data.toString()), 'INFO');
};

// Listen for new messages until timeout is hit
subscription.on('message', messageHandler);

subscription.on('error', (error) => {
console.error(`Error in pubsub subscription: ${error.message}`, {
error, pubSubTopicEnquiry, pubSubSubscriptionId,
});
});

subscription.on('close', () => {
console.error('Pubsub subscription closed', {
pubSubTopicEnquiry, pubSubSubscriptionId,
});
});
})();

process.stdout.write('Done!\n');
}

// stop all other requests
app.use((req: Request, res: Response) => {
Expand Down
47 changes: 47 additions & 0 deletions src/services/httpclient.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import axios from 'axios';

export default class HttpClientCervice {
#axios;

constructor() {
this.#axios = axios;
}

async post(url, body, options, bearer: string = '') {
const headers = {
...(options && options.headers),
Accept: 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
Cookie: 'AspxAutoDetectCookieSupport=1',
};

if (bearer) {
this.#setBearer(bearer);
}

this.#axios.defaults.crossDomain = true;
this.#axios.defaults.withCredentials = true;

try {
const response = await this.#axios.post(url, body, {
...options,
headers,
withCredentials: true,
});

return {
status: 'success',
response: response.data,
};
} catch (error) {
return {
status: 'error',
response: error,
};
}
}

#setBearer(bearer: string) {
this.#axios.defaults.headers.common['Authorization'] = `Bearer ${bearer}`;
}
}
5 changes: 3 additions & 2 deletions src/services/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import LoggingService from './google/LoggingService';
import LoggingService from './log.service';
import HttpClientCervice from './httpclient.service';

export { LoggingService };
export { LoggingService, HttpClientCervice };
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,10 @@ export default class LoggingService {
});
}

sendDataInLogging(data: string, severity: string) {
sendDataInLogging(data: any, severity: string) {
const logMessage = {
details: 'message received',
application: 'gateway-outbound',
messageReceived: data,
data: JSON.parse(JSON.stringify(data, null, 4)),
};
this._logger.setData(logMessage);
this._logger.setSeverity(severity);
Expand Down
25 changes: 25 additions & 0 deletions src/services/mail.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import nodemailer from "nodemailer";

const mailHostname = process.env.MAIL_HOST || '';
const mailPort = parseInt(process.env.MAIL_PORT) || 0;
const mailUsername = process.env.MAIL_USERNAME || '';
const mailPassword = process.env.MAIL_PASSWORD || '';

const transporterOptions = {
host: mailHostname,
port: mailPort,
auth: {
user: mailUsername,
pass: mailPassword,
},
pool: true,
maxConnections: 1,
rateDelta: 20000,
rateLimit: 5,
};

const connectMail = () => {
return nodemailer.createTransport(transporterOptions);
}

export default connectMail;
Loading