Skip to content

Commit 25011db

Browse files
committed
Added EmailRole job handler.
1 parent 9b90f1b commit 25011db

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

ving/jobs/handlers/EmailRole.mjs

+30-3
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,42 @@
11
import ving from '#ving/index.mjs';
2+
import { sendMail } from '#ving/email/send.mjs';
3+
import { useKind } from '#ving/record/utils.mjs';
4+
import { eq } from '#ving/drizzle/orm.mjs';
25

36
/**
47
* This handler looks up all users with a specified role and sends them an email.
58
* @param {Object} job A `BullMQ` job.
69
* @param {Object} job.data An object with data needed for this job.
10+
* @param {string} job.data.role The name of a role on the User record that if true will be sent this email.
11+
* @param {string} job.data.subject The subject line of the email.
12+
* @param {string} job.data.summary A very short summary of the message.
13+
* @param {string} job.data.message The message body of the email.
714
* @returns {boolean} `true`
815
*/
916
export default async function (job) {
10-
ving.log('jobs').debug(`Test ran with data: ${JSON.stringify(job.data)} which is a ${typeof job.data}`);
11-
if (job.data.error) {
12-
throw new Error(job.data.error);
17+
const users = await useKind('User');
18+
const roleUsers = await users.findMany(eq(users.table[job.data.role], true));
19+
ving.log('jobs').info(`${job.id} found ${roleUsers.length} users to send emails to.`);
20+
let succeeded = 0;
21+
let failures = 0;
22+
for (const user of roleUsers) {
23+
const vars = {
24+
subject: job.data.subject,
25+
summary: job.data.summary,
26+
message: job.data.message,
27+
};
28+
try {
29+
await sendMail('generic', {
30+
options: { to: user.get('email') },
31+
vars
32+
});
33+
succeeded++;
34+
}
35+
catch (err) {
36+
failures++;
37+
ving.log('jobs').error(`${job.id} failed to send email to user ${user.get('id')} ${user.get('email')} because ${err.message} with message ${JSON.stringify(vars)}`);
38+
}
1339
}
40+
ving.log('jobs').info(`${job.id} sent ${succeeded} emails with ${failures} failures.`)
1441
return true;
1542
}

ving/jobs/map.mjs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import Test from "#ving/jobs/handlers/Test.mjs";
22
import DeleteUnusedS3File from "#ving/jobs/handlers/DeleteUnusedS3File.mjs";
33
import CronJob from "#ving/jobs/handlers/CronJob.mjs";
4+
import EmailRole from "#ving/jobs/handlers/EmailRole.mjs";
45

56
export const jobHandlers = {
67
Test,
78
DeleteUnusedS3File,
8-
CronJob
9+
CronJob,
10+
EmailRole
911
}

0 commit comments

Comments
 (0)