twitch-clone/backend/src/module/chat/chat.service.ts
2025-07-30 05:23:26 +03:00

72 lines
1.9 KiB
TypeScript

import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '@/src/core/prisma/prisma.service';
import { ChangeChatSettingsInput } from '@/src/module/chat/input/change-chat-settings.input';
import { SendMessageInput } from '@/src/module/chat/input/send-message.input';
import { Stream, User } from '@prisma/generated';
@Injectable()
export class ChatService {
constructor(
public readonly prismaService: PrismaService,
) {
}
public async findMessagesByStream(streamId: Stream['id']) {
return this.prismaService.chatMessage.findMany({
where: { streamId },
orderBy: { createdAt: 'desc' },
include: { user: true },
});
}
public async sendMessage(userId: User['id'], input: SendMessageInput) {
const { text, streamId } = input;
const stream = await this.prismaService.stream.findUnique({
where: { id: streamId },
});
if (!stream) {
throw new NotFoundException('Стрим не найден');
}
if (!stream.isLive) {
throw new BadRequestException('Стрим не запущен');
}
const user = await this.prismaService.user.findUnique({
where: { id: userId },
});
if (!user) {
throw new NotFoundException('Пользователь не найден');
}
return this.prismaService.chatMessage.create({
data: {
user: {
connect: {
id: user.id,
},
},
stream: {
connect: {
id: stream.id,
},
},
text,
},
include: {
stream: true,
},
});
}
public async changeSettings(user: User, input: ChangeChatSettingsInput) {
const { isChatEnable, isChatFollowersOnly, isChatPremiumFollowersOnly } = input;
return this.prismaService.stream.update({
where: { userId: user.id },
data: { isChatEnable, isChatFollowersOnly, isChatPremiumFollowersOnly },
});
}
}