From 8d7f1748db38234a6ba3e773f2525e4ddfeb5358 Mon Sep 17 00:00:00 2001 From: Tzvetan Trave Date: Thu, 23 Oct 2025 23:07:53 +0200 Subject: [PATCH] fixed PATCH avatar --- src/api/user/uAvatar.js | 48 +++++++++++++++-------------------------- 1 file changed, 17 insertions(+), 31 deletions(-) diff --git a/src/api/user/uAvatar.js b/src/api/user/uAvatar.js index 344307e..c3df63a 100644 --- a/src/api/user/uAvatar.js +++ b/src/api/user/uAvatar.js @@ -9,38 +9,24 @@ export async function uAvatar(request, reply, fastify, getUserInfo, setAvatarId, if (!getUserInfo.get(userId)) { return reply.code(404).send({ error: "User does not exist" }); } - deleteAvatarId.run(userId); - const parts = request.parts(); - for await (const part of parts) { - if (part.file) { - let size = 0; - const chunks = []; - for await (const chunk of part.file) { - size += chunk.length; - chunks.push(chunk); - } - if (size === 5 * 1024 * 1024 + 1) { - return reply.code(400).send({ error: "File too large" }); - } - const buffer = Buffer.concat(chunks); - if (!part.filename || part.filename.trim() === '') { - return reply.code(400).send({ error: "Missing filename" }); - } - if (!part.mimetype || part.mimetype.trim() === '') { - return reply.code(400).send({ error: "Missing mimetype" }); - } - const webpBuffer = await sharp(buffer).toFormat('webp').toBuffer(); - const imageId = postImage.run(part.filename, part.mimetype, webpBuffer); - const oldImageId = getAvatarId.get(userId); - if (oldImageId.avatarId !== -1) { - deleteImage.run(oldImageId.avatarId); - deleteAvatarId.run(userId); - } - setAvatarId.run(imageId.lastInsertRowid, userId); - return reply.code(200).send({ msg: "Avatar modified successfully" }); - } + const buffer = request.body; + if (!buffer) { + return reply.code(400).send({ error: "No file uploaded" }); } - return reply.code(400).send({ error: "No avatar modified" }); + if (buffer.length > 5 * 1024 * 1024) { + return reply.code(400).send({ error: "File too large" }); + } + const webpBuffer = await sharp(buffer).toFormat('webp').toBuffer(); + const mimeType = request.headers['content-type']; + const fileName = `avatar_${userId}.webp`; + const imageId = postImage.run(fileName, mimeType, webpBuffer); + const oldImageId = getAvatarId.get(userId); + if (oldImageId.avatarId !== -1) { + deleteImage.run(oldImageId.avatarId); + deleteAvatarId.run(userId); + } + setAvatarId.run(imageId.lastInsertRowid, userId); + return reply.code(200).send({ msg: "Avatar modified successfully" }); } catch (err) { fastify.log.error(err); return reply.code(500).send({ error: "Internal server error" });