-
Notifications
You must be signed in to change notification settings - Fork 7k
Expand file tree
/
Copy pathusers.js
More file actions
36 lines (28 loc) · 937 Bytes
/
users.js
File metadata and controls
36 lines (28 loc) · 937 Bytes
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
const fs = require("fs").promises;
const path = require("path");
const User = require("../models/user");
const jimp = require("jimp");
const avatarsDir = path.join(__dirname, "../public/avatars");
const updateAvatar = async (req, res) => {
try {
const { path: tempUpload, originalname } = req.file;
const { _id: userId } = req.user;
const filename = `${userId}-${originalname}`;
const resultUpload = path.join(avatarsDir, filename);
const image = await jimp.read(tempUpload);
await image.resize(250, 250).writeAsync(resultUpload);
await fs.unlink(tempUpload);
const avatarURL = `/avatars/${filename}`;
const user = await User.findByIdAndUpdate(
userId,
{ avatarURL },
{ new: true }
);
res.status(200).json({
avatarURL: user.avatarURL,
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
module.exports = { updateAvatar };