-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathworker.js
73 lines (56 loc) · 1.82 KB
/
worker.js
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
import Queue from 'bull';
import { ObjectId } from 'mongodb';
import { promises as fsPromises } from 'fs';
import fileUtils from './utils/file';
import userUtils from './utils/user';
import basicUtils from './utils/basic';
const imageThumbnail = require('image-thumbnail');
const fileQueue = new Queue('fileQueue');
const userQueue = new Queue('userQueue');
fileQueue.process(async (job) => {
const { fileId, userId } = job.data;
// Delete bull keys in redis
// redis-cli keys "bull*" | xargs redis-cli del
if (!userId) {
console.log('Missing userId');
throw new Error('Missing userId');
}
if (!fileId) {
console.log('Missing fileId');
throw new Error('Missing fileId');
}
if (!basicUtils.isValidId(fileId) || !basicUtils.isValidId(userId)) throw new Error('File not found');
const file = await fileUtils.getFile({
_id: ObjectId(fileId),
userId: ObjectId(userId),
});
if (!file) throw new Error('File not found');
const { localPath } = file;
const options = {};
const widths = [500, 250, 100];
widths.forEach(async (width) => {
options.width = width;
try {
const thumbnail = await imageThumbnail(localPath, options);
await fsPromises.writeFile(`${localPath}_${width}`, thumbnail);
// console.log(thumbnail);
} catch (err) {
console.error(err.message);
}
});
});
userQueue.process(async (job) => {
const { userId } = job.data;
// Delete bull keys in redis
// redis-cli keys "bull*" | xargs redis-cli del
if (!userId) {
console.log('Missing userId');
throw new Error('Missing userId');
}
if (!basicUtils.isValidId(userId)) throw new Error('User not found');
const user = await userUtils.getUser({
_id: ObjectId(userId),
});
if (!user) throw new Error('User not found');
console.log(`Welcome ${user.email}!`);
});