-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
81 lines (64 loc) · 2.6 KB
/
worker.js
File metadata and controls
81 lines (64 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* eslint-disable import/no-named-as-default */
import { writeFile } from 'fs';
import { promisify } from 'util';
import Queue from 'bull/lib/queue';
import imgThumbnail from 'image-thumbnail';
import mongoDBCore from 'mongodb/lib/core';
import dbClient from './utils/db.js';
import Mailer from './utils/mailer.js';
const writeFileAsync = promisify(writeFile);
const fileQueue = new Queue('thumbnail generation');
const userQueue = new Queue('email sending');
/*
Generate thumbnail for the image with a given width size
*/
const generateThumbnail = async (filePath, size) => {
const buffer = await imgThumbnail(filePath, { width: size });
console.log('Generating file: ${filePath}, size: ${size}');
return writeFileAsync(`${filePath}_${size}`, buffer);
};
//
fileQueue.process(async (job, done) => {
const fileId = job.data.fileId || null;
const userId = job.data.userId || null;
if (!fileId) return done(new Error('Missing fileId'));
if (!userId) return done(new Error('Missing userId'));
console.log('Processing', job.data.name || '');
const file = await (await dbClient.filesCollection()).findOne({
_id: new mongoDBCore.BSON.ObjectId(fileId),
userId: new mongoDBCore.BSON.ObjectId(userId),
});
if (!file) return done(new Error('File not found'));
const sizes = [500, 250, 100];
Promise.all(sizes.map((size) => generateThumbnail(file.localPath, size))).then(() => {
console.log('Thumbnails generated');
done();
});
});
userQueue.process(async (job, done) => {
const userId = job.data.userId || null;
if (!userId) return done(new Error('Missing userId'));
const user = await (await dbClient.usersCollection())
.findOne({ _id: new mongoDBCore.BSON.ObjectId(userId) });
if (!user) return done(new Error('User not found'));
console.log(`Welcome ${user.email}!`);
// send an email to the user with a welcome message
try {
const mailSubject = 'Welcome to The Multilingual Files Manager';
const mailContent = [
'<div>',
'<h3>Hello {{user.name}},</h3>',
'Welcome to <a href="https://github.com/ChernetAsmamaw/Multilingual-File-Manager-Application">',
'Multilingual File Manager</a>, ',
'a simple file management API built with Node.js by ',
'<a href="https://github.com/ChernetAsmamaw">Chernet</a> and ',
'<a href="https://github.com/BevilMulore">Bevil</a>.',
'We hope it meets your needs.',
'</div>',
].join('');
Mailer.sendMail(Mailer.buildMessage(user.email, mailSubject, mailContent));
done();
} catch (err) {
done(err);
}
});