ESLint: Auto reformat and fixing some warnings / errors.

This commit is contained in:
baldo 2022-08-23 20:08:53 +02:00
parent 5237db38e0
commit 91690509d3
50 changed files with 2141 additions and 1493 deletions
server/services

View file

@ -1,10 +1,10 @@
import _ from "lodash";
import moment, {Moment} from "moment";
import {db} from "../db/database";
import moment, { Moment } from "moment";
import { db } from "../db/database";
import Logger from "../logger";
import * as MailTemplateService from "./mailTemplateService";
import * as Resources from "../utils/resources";
import {RestParams} from "../utils/resources";
import { RestParams } from "../utils/resources";
import {
EmailAddress,
isJSONObject,
@ -16,32 +16,31 @@ import {
MailSortField,
MailType,
parseJSON,
UnixTimestampSeconds
UnixTimestampSeconds,
} from "../types";
import ErrorTypes from "../utils/errorTypes";
import {send} from "../mail";
import { send } from "../mail";
type EmaiQueueRow = {
id: MailId,
created_at: UnixTimestampSeconds,
data: string,
email: string,
failures: number,
modified_at: UnixTimestampSeconds,
recipient: EmailAddress,
sender: EmailAddress,
id: MailId;
created_at: UnixTimestampSeconds;
data: string;
email: string;
failures: number;
modified_at: UnixTimestampSeconds;
recipient: EmailAddress;
sender: EmailAddress;
};
const MAIL_QUEUE_DB_BATCH_SIZE = 50;
async function sendMail(options: Mail): Promise<void> {
Logger
.tag('mail', 'queue')
.info(
'Sending pending mail[%d] of type %s. ' +
'Had %d failures before.',
options.id, options.email, options.failures
);
Logger.tag("mail", "queue").info(
"Sending pending mail[%d] of type %s. " + "Had %d failures before.",
options.id,
options.email,
options.failures
);
const renderedTemplate = await MailTemplateService.render(options);
@ -49,21 +48,24 @@ async function sendMail(options: Mail): Promise<void> {
from: options.sender,
to: options.recipient,
subject: renderedTemplate.subject,
html: renderedTemplate.body
html: renderedTemplate.body,
};
await send(mailOptions);
Logger.tag('mail', 'queue').info('Mail[%d] has been send.', options.id);
Logger.tag("mail", "queue").info("Mail[%d] has been send.", options.id);
}
async function findPendingMailsBefore(beforeMoment: Moment, limit: number): Promise<Mail[]> {
async function findPendingMailsBefore(
beforeMoment: Moment,
limit: number
): Promise<Mail[]> {
const rows = await db.all<EmaiQueueRow>(
'SELECT * FROM email_queue WHERE modified_at < ? AND failures < ? ORDER BY id ASC LIMIT ?',
[beforeMoment.unix(), 5, limit],
"SELECT * FROM email_queue WHERE modified_at < ? AND failures < ? ORDER BY id ASC LIMIT ?",
[beforeMoment.unix(), 5, limit]
);
return rows.map(row => {
return rows.map((row) => {
const mailType = row.email;
if (!isMailType(mailType)) {
throw new Error(`Invalid mailtype in database: ${mailType}`);
@ -84,13 +86,15 @@ async function findPendingMailsBefore(beforeMoment: Moment, limit: number): Prom
}
async function removePendingMailFromQueue(id: MailId): Promise<void> {
await db.run('DELETE FROM email_queue WHERE id = ?', [id]);
await db.run("DELETE FROM email_queue WHERE id = ?", [id]);
}
async function incrementFailureCounterForPendingEmail(id: MailId): Promise<void> {
async function incrementFailureCounterForPendingEmail(
id: MailId
): Promise<void> {
await db.run(
'UPDATE email_queue SET failures = failures + 1, modified_at = ? WHERE id = ?',
[moment().unix(), id],
"UPDATE email_queue SET failures = failures + 1, modified_at = ? WHERE id = ?",
[moment().unix(), id]
);
}
@ -99,7 +103,10 @@ async function sendPendingMail(pendingMail: Mail): Promise<void> {
await sendMail(pendingMail);
} catch (error) {
// we only log the error and increment the failure counter as we want to continue with pending mails
Logger.tag('mail', 'queue').error('Error sending pending mail[' + pendingMail.id + ']:', error);
Logger.tag("mail", "queue").error(
"Error sending pending mail[" + pendingMail.id + "]:",
error
);
await incrementFailureCounterForPendingEmail(pendingMail.id);
return;
@ -109,22 +116,29 @@ async function sendPendingMail(pendingMail: Mail): Promise<void> {
}
async function doGetMail(id: MailId): Promise<Mail> {
const row = await db.get<Mail>('SELECT * FROM email_queue WHERE id = ?', [id]);
const row = await db.get<Mail>("SELECT * FROM email_queue WHERE id = ?", [
id,
]);
if (row === undefined) {
throw {data: 'Mail not found.', type: ErrorTypes.notFound};
throw { data: "Mail not found.", type: ErrorTypes.notFound };
}
return row;
}
export async function enqueue(sender: string, recipient: string, email: MailType, data: MailData): Promise<void> {
export async function enqueue(
sender: string,
recipient: string,
email: MailType,
data: MailData
): Promise<void> {
if (!_.isPlainObject(data)) {
throw new Error('Unexpected data: ' + data);
throw new Error("Unexpected data: " + data);
}
await db.run(
'INSERT INTO email_queue ' +
'(failures, sender, recipient, email, data) ' +
'VALUES (?, ?, ?, ?, ?)',
[0, sender, recipient, email, JSON.stringify(data)],
"INSERT INTO email_queue " +
"(failures, sender, recipient, email, data) " +
"VALUES (?, ?, ?, ?, ?)",
[0, sender, recipient, email, JSON.stringify(data)]
);
}
@ -132,10 +146,12 @@ export async function getMail(id: MailId): Promise<Mail> {
return await doGetMail(id);
}
export async function getPendingMails(restParams: RestParams): Promise<{ mails: Mail[], total: number }> {
export async function getPendingMails(
restParams: RestParams
): Promise<{ mails: Mail[]; total: number }> {
const row = await db.get<{ total: number }>(
'SELECT count(*) AS total FROM email_queue',
[],
"SELECT count(*) AS total FROM email_queue",
[]
);
const total = row?.total || 0;
@ -144,18 +160,18 @@ export async function getPendingMails(restParams: RestParams): Promise<{ mails:
restParams,
MailSortField.ID,
isMailSortField,
['id', 'failures', 'sender', 'recipient', 'email']
["id", "failures", "sender", "recipient", "email"]
);
const mails = await db.all(
'SELECT * FROM email_queue WHERE ' + filter.query,
filter.params,
"SELECT * FROM email_queue WHERE " + filter.query,
filter.params
);
return {
mails,
total
}
total,
};
}
export async function deleteMail(id: MailId): Promise<void> {
@ -164,29 +180,32 @@ export async function deleteMail(id: MailId): Promise<void> {
export async function resetFailures(id: MailId): Promise<Mail> {
const statement = await db.run(
'UPDATE email_queue SET failures = 0, modified_at = ? WHERE id = ?',
[moment().unix(), id],
"UPDATE email_queue SET failures = 0, modified_at = ? WHERE id = ?",
[moment().unix(), id]
);
if (!statement.changes) {
throw new Error('Error: could not reset failure count for mail: ' + id);
throw new Error("Error: could not reset failure count for mail: " + id);
}
return await doGetMail(id);
}
export async function sendPendingMails(): Promise<void> {
Logger.tag('mail', 'queue').debug('Start sending pending mails...');
Logger.tag("mail", "queue").debug("Start sending pending mails...");
const startTime = moment();
while (true) {
Logger.tag('mail', 'queue').debug('Sending next batch...');
Logger.tag("mail", "queue").debug("Sending next batch...");
const pendingMails = await findPendingMailsBefore(startTime, MAIL_QUEUE_DB_BATCH_SIZE);
const pendingMails = await findPendingMailsBefore(
startTime,
MAIL_QUEUE_DB_BATCH_SIZE
);
if (_.isEmpty(pendingMails)) {
Logger.tag('mail', 'queue').debug('Done sending pending mails.');
Logger.tag("mail", "queue").debug("Done sending pending mails.");
return;
}