Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const up = (knex) =>
knex.schema.alterTable('invites', (table) => {
table.enum('email_status', ['error', 'pending', 'success']);
});

export const down = (knex) =>
knex.schema.alterTable('invites', (table) => {
table.dropColumn('email_status');
});
6 changes: 6 additions & 0 deletions api/src/config/globals.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,9 @@ export const invitesStatuses = {
PENDING: 'pending',
SUCCESS: 'success',
};

export const emailStatuses = {
ERROR: 'error',
PENDING: 'pending',
SUCCESS: 'success',
};
2 changes: 1 addition & 1 deletion api/src/models/Invite.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
invitesServiceErrors,
invitesStatuses,
lessonServiceErrors as errors,
resources,
} from '../config';

class Invite extends BaseModel {
Expand All @@ -21,6 +20,7 @@ class Invite extends BaseModel {
resourceType: { type: 'string' },
status: { type: 'string' },
email: { type: 'string' },
emailStatus: { type: 'string' },
createdAt: { type: 'string' },
},
};
Expand Down
23 changes: 2 additions & 21 deletions api/src/services/invites/controllers/createInvite.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,24 +50,12 @@ const options = {
},
};

async function sendInvites({ emailModel, data, host }) {
return Promise.all(
data.map(async (invite) =>
emailModel.sendInvite({
email: invite.email,
link: `${host}/invite/${invite.id}`,
}),
),
);
}

async function handler({ body }) {
const {
models: { Invite },
config: {
globals: { invitesStatuses },
globals: { invitesStatuses, emailStatuses },
},
emailModel,
} = this;

const invites = await Invite.transaction(async (trx) => {
Expand All @@ -83,6 +71,7 @@ async function handler({ body }) {
resource_id: body.resourceId,
resource_type: body.resourceType,
status: invitesStatuses.PENDING,
email_status: emailStatuses.PENDING,
email,
}))
: {
Expand All @@ -93,14 +82,6 @@ async function handler({ body }) {

const createdInvites = await Invite.createInvites({ trx, data });

if (data.length) {
await sendInvites({
emailModel,
data: createdInvites,
host: process.env.SB_HOST,
});
}

return createdInvites;
});

Expand Down
7 changes: 7 additions & 0 deletions backend.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ services:
volumes:
- ./storage:/data
command: server --address 0.0.0.0:9000 --console-address 0.0.0.0:9001 /data
scheduler:
command: yarn run:dev
volumes:
- ./scheduler:/scheduler
- /scheduler/node_modules
environment:
DATABASE_URL: ${POSTGRES_URI}
api:
command: yarn run:dev
ports:
Expand Down
9 changes: 9 additions & 0 deletions base.dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ services:
environment:
MINIO_ROOT_USER: ${S3_ACCESS_KEY}
MINIO_ROOT_PASSWORD: ${S3_SECRET_KEY}
scheduler:
build:
context: ./scheduler
dockerfile: .docker/Dockerfile
restart: always
depends_on:
- db
environment:
HOST: ${SB_HOST}
api:
build:
context: ./api
Expand Down
7 changes: 7 additions & 0 deletions scheduler/.docker/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM node:14-alpine

WORKDIR /scheduler

COPY package.json yarn.lock ./
RUN yarn
COPY . .
37 changes: 37 additions & 0 deletions scheduler/email.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import mailer from 'nodemailer';
import { DEFAULT_LANGUAGE } from './scheduler.js';

export class Email {
constructor({ i18n }) {
this.t = i18n.t.bind(i18n);
this.transporter = mailer.createTransport({
pool: true,
host: 'smtp.gmail.com',
port: process.env.SMTP_PORT || 465,
secure: true,
auth: {
user: process.env.SB_MAIL_USER,
pass: process.env.SB_MAIL_PASSWORD,
},
});
}

static getMailMocked({ ...params }) {
return {
from: 'StudyBites',
...params,
};
}

async sendMailWithLogging(params) {
console.log(Email.getMailMocked(params));
}

async sendInvite({ email, link, language = DEFAULT_LANGUAGE }) {
return this.sendMailWithLogging({
to: email,
subject: this.t('email:invite.subject', { lng: language }),
html: this.t('email:invite.html', { lng: language, link }),
});
}
}
18 changes: 18 additions & 0 deletions scheduler/locales/en/email.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"password_reset": {
"subject": "Password reset",
"html": "Reset password link {{link}}"
},
"password_changed": {
"subject": "Password changed",
"html": "Your password were successfully changed"
},
"email_confirmation": {
"subject": "Email confirmation",
"html": "Confirm email link {{link}}"
},
"invite": {
"subject": "You were invited to start learning at StudyBites",
"html": "Follow the link to start: {{link}}"
}
}
18 changes: 18 additions & 0 deletions scheduler/locales/ru/email.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"password_reset": {
"subject": "Восстановление пароля",
"html": "Ссылка для восстановления пароля {{link}}"
},
"password_changed": {
"subject": "Пароль изменен",
"html": "Ваш пароль был успешно изменен."
},
"email_confirmation": {
"subject": "Email подтверждение",
"html": "Подтвердите ссылку на электронную почту {{link}}"
},
"invite": {
"subject": "Вас пригласили начать обучение на StudyBites",
"html": "Пройдите по ссылке, чтобы начать: {{link}}"
}
}
21 changes: 21 additions & 0 deletions scheduler/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "scheduler",
"version": "0.1.0",
"main": "scheduler.js",
"type": "module",
"license": "Apache-2.0",
"scripts": {
"run:dev": "yarn && nodemon scheduler.js"
},
"dependencies": {
"i18next": "^21.3.3",
"i18next-fs-backend": "^1.1.1",
"knex": "^0.95.11",
"node-cron": "^3.0.0",
"nodemailer": "^6.7.0",
"pg": "^8.7.1"
},
"devDependencies": {
"nodemon": "^2.0.14"
}
}
75 changes: 75 additions & 0 deletions scheduler/scheduler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import knex from 'knex';
import cron from 'node-cron';
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
import { Email } from './email.js';

export const DEFAULT_LANGUAGE = 'en';
export const LANGUAGES_LIST = ['en', 'ru'];

class Scheduler {
constructor({ i18n }) {
this.mailer = new Email({ i18n });
}

async start() {
try {
await this.connDB();
// invite job will run every one minute
cron.schedule('* * * * *', this.inviteJob, {});
console.log('scheduler started successfully');
} catch (e) {
console.log(e);
process.exit(1);
}
}

async connDB() {
this.db = knex({
client: 'pg',
connection: process.env.DATABASE_URL,
});
await this.db.raw('SELECT 1');
}

inviteJob = async () => {
try {
const pendingInvites = await this.db('invites').where({
status: 'pending',
email_status: 'pending',
});
pendingInvites.map(async (invite) => {
await this.mailer.sendInvite({
email: invite.email,
link: `${process.env.HOST}/invite/${invite.id}`,
});
await this.db('invites').where({ id: invite.id }).update({
email_status: 'success',
});
});
} catch (e) {
console.log('invite job failed:', e);
}
};
}

(async () => {
await i18next.use(Backend).init({
initImmediate: false,
lng: DEFAULT_LANGUAGE,
fallbackLng: DEFAULT_LANGUAGE,
preload: LANGUAGES_LIST,
ns: ['email'],
keySeparator: '.',
interpolation: {
escapeValue: false,
},
backend: {
loadPath: `locales/{{lng}}/{{ns}}.json`,
},
});
const scheduler = new Scheduler({
i18n: i18next,
});
await scheduler.start();
})();
Loading