fixed avatars bloating DB when successive POST occured

This commit is contained in:
Tzvetan Trave
2025-10-25 09:42:26 +02:00
parent 41cafaf8e7
commit c792254f9c
2 changed files with 8 additions and 2 deletions

View File

@ -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);

View File

@ -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" });