75 lines
2.0 KiB
TypeScript
75 lines
2.0 KiB
TypeScript
import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
import { CreateCharacterDto, UpdateCharacterDto } from './dto/create-character.dto';
|
|
import { Character } from '@prisma/client';
|
|
|
|
@Injectable()
|
|
export class CharacterService {
|
|
constructor(private prisma: PrismaService) {}
|
|
|
|
async create(userId: string, createCharacterDto: CreateCharacterDto): Promise<Character> {
|
|
return this.prisma.character.create({
|
|
data: {
|
|
...createCharacterDto,
|
|
userId,
|
|
},
|
|
});
|
|
}
|
|
|
|
async findAllByUser(userId: string): Promise<Character[]> {
|
|
return this.prisma.character.findMany({
|
|
where: { userId },
|
|
orderBy: { createdAt: 'desc' },
|
|
});
|
|
}
|
|
|
|
async findById(id: string, userId?: string): Promise<Character> {
|
|
const character = await this.prisma.character.findUnique({
|
|
where: { id },
|
|
include: {
|
|
knowledgeSources: true,
|
|
},
|
|
});
|
|
|
|
if (!character) {
|
|
throw new NotFoundException('Character not found');
|
|
}
|
|
|
|
// If userId is provided, check if user owns the character or if it's public
|
|
if (userId && character.userId !== userId && !character.isPublic) {
|
|
throw new ForbiddenException('You do not have access to this character');
|
|
}
|
|
|
|
return character;
|
|
}
|
|
|
|
async update(
|
|
id: string,
|
|
userId: string,
|
|
updateCharacterDto: UpdateCharacterDto,
|
|
): Promise<Character> {
|
|
const character = await this.findById(id, userId);
|
|
|
|
if (character.userId !== userId) {
|
|
throw new ForbiddenException('You can only update your own characters');
|
|
}
|
|
|
|
return this.prisma.character.update({
|
|
where: { id },
|
|
data: updateCharacterDto,
|
|
});
|
|
}
|
|
|
|
async delete(id: string, userId: string): Promise<void> {
|
|
const character = await this.findById(id, userId);
|
|
|
|
if (character.userId !== userId) {
|
|
throw new ForbiddenException('You can only delete your own characters');
|
|
}
|
|
|
|
await this.prisma.character.delete({
|
|
where: { id },
|
|
});
|
|
}
|
|
}
|