merged image API in user API

This commit is contained in:
Tzvetan Trave
2025-10-22 19:46:25 +02:00
parent 300e5a2b33
commit 6a08241493
12 changed files with 228 additions and 187 deletions

View File

@ -1,17 +1,37 @@
export async function pAvatar(request, reply, fastify, getUserInfo, setAvatarId) {
import sharp from 'sharp';
export async function pAvatar(request, reply, fastify, getUserInfo, setAvatarId, postImage) {
try {
const userId = request.params.userId;
if (!getUserInfo.get(userId)) {
return reply.cose(404).send({ error: "User does not exist" });
}
console.log("====================================\n", request.headers);//==========
const res = await fetch('http://localhost:3004/images', { method: "POST", headers: { "Content-Type": "image/webp" }, body: request.body ? JSON.stringify(request.body) : undefined });
if (!res.ok) {
return reply.code(500).send({ error: "Internal server error" });
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 === 2 * 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);
setAvatarId.run(imageId.lastInsertRowid, userId);
return reply.code(200).send({ msg: "Avatar uploaded successfully" });
}
}
const data = await res.json();
setAvatarId.run(data.imageId, userId);
return reply.code(200).send({ msg: "Avatar uploaded successfully" });
return reply.code(400).send({ error: "No avatar uploaded" });
} catch (err) {
fastify.log.error(err);
return reply.code(500).send({ error: "Internal server error" });