Skip to content

Commit 956b8a1

Browse files
author
Hamid Tavakoli
committed
Merge branch 'master' of github.com:topcoder-platform/tc-email-service
2 parents 714ba1a + c13bba3 commit 956b8a1

23 files changed

+3523
-2693
lines changed

.eslintrc

Lines changed: 0 additions & 3 deletions
This file was deleted.

.eslintrc.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module.exports = {
2+
"parserOptions": {
3+
"ecmaVersion": 12,
4+
"env": {
5+
"node": true,
6+
"es2021": true
7+
}
8+
}
9+
}

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
node_modules
22
.env
3+
log.txt

Dockerfile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
# and runs it against the specified Topcoder backend (development or
33
# production) when container is executed.
44

5-
FROM node:6.10
5+
6+
FROM node:16.17
67
LABEL app="tc email" version="1.1"
78

89
WORKDIR /opt/app

config/default.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
/**
22
* The configuration file.
33
*/
4+
require('dotenv').config()
45
module.exports = {
56
LOG_LEVEL: process.env.LOG_LEVEL,
67
PORT: process.env.PORT,
78
AUTH_SECRET: process.env.AUTH_SECRET,
89
DATABASE_URL: process.env.DATABASE_URL,
910
DATABASE_OPTIONS: {
1011
dialect: 'postgres',
12+
logging: false,
1113
dialectOptions: {
1214
ssl: process.env.DATABASE_SSL != null,
1315
},
@@ -34,18 +36,21 @@ module.exports = {
3436
TEMPLATE_MAP: process.env.TEMPLATE_MAP,
3537
SENDGRID_API_KEY: process.env.SENDGRID_API_KEY || '',
3638
EMAIL_FROM: process.env.EMAIL_FROM || 'no-reply@topcoder.com',
37-
39+
3840
// temporary not in use feature
3941
EMAIL_MAX_ERRORS: process.env.EMAIL_MAX_ERRORS || 2,
4042
EMAIL_PAUSE_TIME: process.env.EMAIL_PAUSE_TIME || 30,
4143

4244
//in every 2 minutes will retry for failed status
4345
EMAIL_RETRY_SCHEDULE: process.env.EMAIL_RETRY_SCHEDULE || '0 */2 * * * *',
4446
//wont't retry failed emails older than this time (msec)
45-
EMAIL_RETRY_MAX_AGE: process.env.EMAIL_RETRY_MAX_AGE || 1000*60*60*24,
47+
EMAIL_RETRY_MAX_AGE: process.env.EMAIL_RETRY_MAX_AGE || 1000 * 60 * 60 * 24,
4648

4749
API_CONTEXT_PATH: process.env.API_CONTEXT_PATH || '/v5/email',
4850

4951
PAYLOAD_SENDGRID_TEMPLATE_KEY: process.env.PAYLOAD_SENDGRID_TEMPLATE_KEY || 'sendgrid_template_id',
50-
52+
//Tracing information
53+
APM_OTLP_TRACE_EXPORTER_URL: process.env.APM_OTLP_TRACE_EXPORTER_URL || '',
54+
APM_SERVICE_NAME: process.env.APM_SERVICE_NAME || 'tc-email-service-svc',
55+
APM_TRACER_NAME: process.env.APM_TRACER_NAME || 'tc-email-service-svc',
5156
};

connect/connectEmailServer.js

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
/**
22
* This is TopCoder connect email server.
33
*/
4-
'use strict';
5-
6-
global.Promise = require('bluebird');
7-
84
const _ = require('lodash');
95
const config = require('config');
106
const emailServer = require('../index');
@@ -13,27 +9,27 @@ const logger = require('../src/common/logger');
139

1410
// set configuration for the server, see ../config/default.js for available config parameters
1511
// setConfig should be called before initDatabase and start functions
16-
emailServer.setConfig({ LOG_LEVEL: 'debug' });
12+
emailServer.setConfig({ LOG_LEVEL: config.LOG_LEVEL });
1713

1814
// add topic handlers,
1915
// handler is used build a notification list for a message of a topic,
20-
// it is defined as: function(topic, message, callback),
16+
// it is defined as: function(topic, message),
2117
// the topic is topic name,
2218
// the message is JSON event message,
23-
// the callback is function(error, templateId), where templateId is the used SendGrid template id
24-
const handler = (topic, message, callback) => {
19+
const handler = async (topic, message) => {
2520
let templateId = config.TEMPLATE_MAP[topic];
2621
templateId = _.get(message, config.PAYLOAD_SENDGRID_TEMPLATE_KEY, templateId);
2722
if (!templateId) {
28-
return callback(null, { success: false, error: `Template not found for topic ${topic}` });
23+
return { success: false, error: `Template not found for topic ${topic}` };
2924
}
3025

31-
service.sendEmail(templateId, message).then(() => {
32-
callback(null, { success: true });
33-
}).catch((err) => {
34-
logger.error("Error occurred in sendgrid api calling:", err);
35-
callback(null, { success: false, error: err });
36-
});
26+
try {
27+
await service.sendEmail(templateId, message)
28+
return { success: true };
29+
} catch (err) {
30+
logger.error("Error occurred in sendgrid api calling:", err);
31+
return { success: false, error: err };
32+
}
3733

3834
};
3935

@@ -45,8 +41,15 @@ _.keys(config.TEMPLATE_MAP).forEach((eventType) => {
4541
// init database, it will clear and re-create all tables
4642
emailServer
4743
.initDatabase()
48-
.then(() => emailServer.start())
49-
.catch((e) => console.log(e)); // eslint-disable-line no-console
44+
.then(() => {
45+
logger.info('Database initialized successfully.')
46+
47+
emailServer.start()
48+
})
49+
.catch((e) => {
50+
logger.error('Error occurred in starting email server:', e);
51+
process.exit(1);
52+
}); // eslint-disable-line no-console
5053

5154
// if no need to init database, then directly start the server:
52-
// emailServer.start();
55+
// emailServer.start()

connect/service.js

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,44 @@
11
/**
22
* This is TopCoder connect email service.
33
*/
4-
'use strict';
54

65
const sgMail = require('@sendgrid/mail');
76
const config = require('config');
7+
const logger = require('../src/common/logger');
88

99
// set api key for SendGrid email client
1010
sgMail.setApiKey(config.SENDGRID_API_KEY);
1111

12-
const sendEmail = (templateId, message) => { // send email
13-
12+
const sendEmail = async (templateId, message) => { // send email
13+
const span = await logger.startSpan('sendEmail');
14+
let msg = {}
1415
const from = message.from ? message.from : config.EMAIL_FROM;
1516
const replyTo = message.replyTo ? message.replyTo : config.EMAIL_FROM;
16-
const substitutions = message.data ;
17-
const categories = message.categories ? message.categories: [];
17+
const substitutions = message.data;
18+
const categories = message.categories ? message.categories : [];
1819
const to = message.recipients;
19-
const cc = message.cc ? message.cc : [];
20+
const cc = message.cc ? message.cc : [];
2021
const bcc = message.bcc ? message.bcc : [];
21-
22-
if (message.version && message.version=="v3"){
23-
return sgMail.send({
22+
const sendAt = message.sendAt ? message.sendAt : undefined;
23+
const personalizations = message.personalizations ? message.personalizations : undefined
24+
const attachments = message.attachments ? message.attachments : [];
25+
26+
if (message.version && message.version == "v3") {
27+
msg = {
2428
to,
2529
templateId,
2630
dynamicTemplateData: substitutions,
31+
personalizations,
2732
from,
2833
replyTo,
2934
categories,
3035
cc,
3136
bcc,
32-
});
33-
} else{
34-
return sgMail.send({
37+
attachments,
38+
sendAt
39+
};
40+
} else {
41+
msg = {
3542
to,
3643
templateId,
3744
substitutions,
@@ -41,9 +48,22 @@ const sendEmail = (templateId, message) => { // send email
4148
categories,
4249
cc,
4350
bcc,
44-
});
51+
};
52+
}
53+
logger.info(`Sending email with templateId: ${templateId} and message: ${JSON.stringify(msg)}`);
54+
try {
55+
await logger.endSpan(span);
56+
const sgSpan = await logger.startSpan('sendgrid');
57+
const result = await sgMail.send(msg)
58+
await logger.endSpan(sgSpan);
59+
logger.info(`Email sent successfully with result: ${JSON.stringify(result)} \n ${JSON.stringify(msg)}`);
60+
return result
61+
} catch (err) {
62+
logger.error(`Error occurred in sendgrid api calling: ${err}`);
63+
throw err
4564
}
4665
}
4766
module.exports = {
4867
sendEmail,
4968
}
69+
logger.buildService(module.exports)

docs/swagger_api.yaml

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ info:
44
description: "TOPCODER EMAIL SERIES - EMAIL SERVER"
55
version: "1.0.0"
66
host: "localhost:6100"
7-
basePath : "/v5/email"
7+
basePath: "/v5/email"
88
schemes:
9-
- "https"
9+
- "https"
1010
securityDefinitions:
1111
jwt:
1212
type: apiKey
@@ -17,8 +17,7 @@ securityDefinitions:
1717
paths:
1818
/health:
1919
get:
20-
description:
21-
health check endpoint
20+
description: health check endpoint
2221
produces:
2322
- application/json
2423
responses:

0 commit comments

Comments
 (0)