From c792254f9c477d683b66a88d9fae934ed84fbd83 Mon Sep 17 00:00:00 2001 From: Tzvetan Trave Date: Sat, 25 Oct 2025 09:42:26 +0200 Subject: [PATCH] fixed avatars bloating DB when successive POST occured --- src/api/user/default.js | 2 +- src/api/user/pAvatar.js | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/api/user/default.js b/src/api/user/default.js index 88c7a4e..cedcf01 100644 --- a/src/api/user/default.js +++ b/src/api/user/default.js @@ -229,7 +229,7 @@ export default async function(fastify, options) { return pMatchHistory(request, reply, fastify, getUserInfo, addMatch, incWinsPong, incLossesPong, incWinsTetris, incLossesTetris); }); fastify.post('/users/:userId/avatar', { bodyLimit: 5242880, preHandler: [fastify.authenticate] }, async (request, reply) => { - return pAvatar(request, reply, fastify, getUserInfo, setAvatarId, postImage); + return pAvatar(request, reply, fastify, getUserInfo, getAvatarId, setAvatarId, deleteAvatarId, postImage, deleteImage); }); fastify.post('/ping', { preHandler: [fastify.authenticate] }, async (request, reply) => { return pPing(request, reply, fastify, setActivityTime); diff --git a/src/api/user/pAvatar.js b/src/api/user/pAvatar.js index f90299e..7515052 100644 --- a/src/api/user/pAvatar.js +++ b/src/api/user/pAvatar.js @@ -5,7 +5,7 @@ import sharp from 'sharp'; * @param {import('fastify').FastifyReply} reply * @param {import('fastify').FastifyInstance} fastify */ -export async function pAvatar(request, reply, fastify, getUserInfo, setAvatarId, postImage) { +export async function pAvatar(request, reply, fastify, getUserInfo, getAvatarId, setAvatarId, deleteAvatarId, postImage, deleteImage) { try { const userId = request.params.userId; if (request.user !== userId && request.user !== 'admin') { @@ -35,6 +35,12 @@ export async function pAvatar(request, reply, fastify, getUserInfo, setAvatarId, 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 uploaded successfully" });