import { PrismaService } from '@/src/core/prisma/prisma.service' import { ChangeProfileInfoInput } from '@/src/module/auth/profile/inputs/change-profile-info.input' import { ConflictException, Injectable } from '@nestjs/common' import sharp from 'sharp' import { StorageService } from '../../libs/storage/storage.service' import { User } from '@/prisma/generated' import * as Upload from 'graphql-upload/Upload.js' @Injectable() export class ProfileService { constructor( private readonly prismaService: PrismaService, private readonly storageService: StorageService, ) { } public async changeAvatar(user: User, file: Upload) { if (user.avatar) { await this.storageService.remove(user.avatar) } const chunks: Buffer[] = [] for await (const chunk of file.createReadStream()) { chunks.push(chunk) } const buffer = Buffer.concat(chunks) const fileName = `/channels/${user.name}.webp` const processedBuffer = await sharp(buffer, { animated: file.filename.endsWith('.gif') }) .resize(512, 512) .webp() .toBuffer() await this.storageService.upload(processedBuffer, fileName, 'image/webp') await this.prismaService.user.update({ where: { id: user.id }, data: { avatar: fileName }, }) return true } public async removeAvatar(user: User) { if (!user.avatar) { return true } await this.storageService.remove(user.avatar) await this.prismaService.user.update({ where: { id: user.id }, data: { avatar: null }, }) return true } public async changeInfo(user: User, input: ChangeProfileInfoInput) { const { bio = user.bio, displayName = user.displayName, name = user.name } = input const existingUser = await this.prismaService.user.findUnique({ where: { name }, }) if (existingUser && user.name !== name) { throw new ConflictException('Пользователь с таким именем уже существует') } return this.prismaService.user.update({ where: { id: user.id }, data: { bio, displayName, name }, }) } }