feat: add i18n and avatar upload

This commit is contained in:
Vaka.pro
2026-04-26 22:16:59 +03:00
parent db41d4a246
commit 1b23097b18
22 changed files with 750 additions and 145 deletions

View File

@@ -25,6 +25,20 @@ export async function saveUploadedImage(
return { imageUrl: relative };
}
export async function saveUploadedAvatar(
userId: string,
mime: string,
buffer: Buffer,
): Promise<{ imageUrl: string }> {
const ext = MIME_TO_EXT[mime];
if (!ext) throw new ValidationError('Unsupported image type');
const filename = `${userId}-${nanoid(8)}.${ext}`;
const relative = `/uploads/avatar/${filename}`;
const absPath = resolve(env.UPLOADS_DIR, 'avatar', filename);
await writeFile(absPath, buffer);
return { imageUrl: relative };
}
export async function deleteLocalImageIfAny(imageUrl: string | null): Promise<void> {
if (!imageUrl) return;
if (!imageUrl.startsWith('/uploads/')) return;

View File

@@ -1,7 +1,10 @@
import type { FastifyInstance } from 'fastify';
import { updateProfileSchema } from '@family-wishlist/shared';
import { ConflictError, NotFoundError } from '../../utils/errors.js';
import { ConflictError, NotFoundError, ValidationError } from '../../utils/errors.js';
import { Prisma } from '@prisma/client';
import { deleteLocalImageIfAny, saveUploadedAvatar } from '../images/storage.service.js';
const MAX_AVATAR_BYTES = 2 * 1024 * 1024;
export default async function profileRoutes(app: FastifyInstance) {
app.addHook('preHandler', app.authenticate);
@@ -27,4 +30,25 @@ export default async function profileRoutes(app: FastifyInstance) {
throw err;
}
});
app.post('/avatar', async (request) => {
const current = await app.prisma.user.findUnique({ where: { id: request.user.id } });
if (!current) throw new NotFoundError('Profile');
const data = await request.file();
if (!data) throw new ValidationError('No file uploaded');
const buffer = await data.toBuffer();
if (buffer.byteLength > MAX_AVATAR_BYTES) {
throw new ValidationError('Avatar must be 2 MB or less');
}
const { imageUrl } = await saveUploadedAvatar(request.user.id, data.mimetype, buffer);
await deleteLocalImageIfAny(current.avatarUrl);
return app.prisma.user.update({
where: { id: request.user.id },
data: { avatarUrl: imageUrl },
});
});
}