1
0
forked from noxious/server

Character name field is always unique, updated init migration

This commit is contained in:
Dennis Postma 2024-06-02 22:09:36 +02:00
parent 9223afe9f1
commit c25b21c5c7
4 changed files with 23 additions and 1 deletions

View File

@ -23,6 +23,7 @@ CREATE TABLE `Character` (
`rotation` INTEGER NOT NULL,
`zoneId` INTEGER NOT NULL,
UNIQUE INDEX `Character_name_key`(`name`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

View File

@ -30,7 +30,7 @@ model Character {
id Int @id @default(autoincrement())
userId Int
user User @relation(fields: [userId], references: [id])
name String
name String @unique
hitpoints Int @default(100)
mana Int @default(100)
level Int @default(1)

View File

@ -11,6 +11,14 @@ export default function (socket: TSocket, io: Server) {
data = ZCharacterCreate.parse(data);
const user_id = socket.user?.id as number;
// Check if character name already exists
const characterExists = await CharacterRepository.getByName(data.name);
if (characterExists) {
return socket.emit('notification', {message: 'Character name already exists'});
}
const character: Character = await CharacterRepository.create(user_id, data.name) as Character;
const characters: Character[] = await CharacterRepository.getByUserId(user_id) as Character[];

View File

@ -59,6 +59,19 @@ class CharacterRepository {
throw new Error(`Failed to delete character: ${error.message}`);
}
}
async getByName(name: string): Promise<Character | null> {
try {
return await prisma.character.findFirst({
where: {
name,
},
});
} catch (error: any) {
// Handle error
throw new Error(`Failed to get character by name: ${error.message}`);
}
}
}
export default new CharacterRepository;