58 lines
1.4 KiB
JavaScript
58 lines
1.4 KiB
JavaScript
const fs = require("fs")
|
|
const { uploadImage } = require("./uploadImage.service")
|
|
const { makeWebp } = require("../utils/processImage")
|
|
const { validateImage } = require("../utils/validateImage")
|
|
|
|
const userDB = require("../db/user.db")
|
|
const { setUserPublicInRedis } = require("./redis/userPublicCache.service")
|
|
|
|
async function updateUserAvatar(userId, file) {
|
|
if (!file) {
|
|
throw new Error("No file uploaded")
|
|
}
|
|
|
|
validateImage({
|
|
mimetype: file.mimetype,
|
|
size: file.size,
|
|
})
|
|
|
|
const buffer = fs.readFileSync(file.path)
|
|
const webpBuffer = await makeWebp(buffer, { quality: 80 })
|
|
|
|
const imageUrl = await uploadImage({
|
|
bucket: "avatars",
|
|
path: `${userId}_${Date.now()}.webp`,
|
|
fileBuffer: webpBuffer,
|
|
contentType: "image/webp",
|
|
})
|
|
|
|
fs.unlinkSync(file.path)
|
|
|
|
const updated = await updateAvatarUrl(userId, imageUrl)
|
|
await setUserPublicInRedis(updated, { ttlSeconds: 60 * 60 })
|
|
return updated
|
|
}
|
|
|
|
|
|
async function updateAvatarUrl(userId, imageUrl) {
|
|
return userDB.updateUser(
|
|
{ id: userId },
|
|
{ avatarUrl: imageUrl },
|
|
{
|
|
select: {
|
|
id: true,
|
|
username: true,
|
|
avatarUrl: true,
|
|
userBadges: {
|
|
orderBy: { earnedAt: "desc" },
|
|
select: {
|
|
earnedAt: true,
|
|
badge: { select: { id: true, name: true, iconUrl: true, description: true } },
|
|
},
|
|
},
|
|
},
|
|
}
|
|
)
|
|
}
|
|
module.exports = { updateUserAvatar }
|