66 lines
2.6 KiB
TypeScript
66 lines
2.6 KiB
TypeScript
import { z } from 'zod';
|
|
import useDatabase from '~/composables/useDatabase';
|
|
import { characterAbilitiesTable, characterLevelingTable, characterModifiersTable, characterSpellsTable, characterTable, characterTrainingTable } from '~/db/schema';
|
|
import { CharacterValidation, type Ability, type DoubleIndex, type MainStat, type TrainingLevel } from '~/types/character';
|
|
|
|
|
|
export default defineEventHandler(async (e) => {
|
|
const body = await readValidatedBody(e, CharacterValidation.extend({ id: z.unknown(), }).safeParse);
|
|
if(!body.success)
|
|
{
|
|
setResponseStatus(e, 400);
|
|
return body.error.message;
|
|
}
|
|
|
|
const session = await getUserSession(e);
|
|
if(!session.user || session.user.state !== 1)
|
|
{
|
|
setResponseStatus(e, 401);
|
|
return;
|
|
}
|
|
|
|
const db = useDatabase();
|
|
|
|
try
|
|
{
|
|
const id = db.transaction((tx) => {
|
|
const id = tx.insert(characterTable).values({
|
|
name: body.data.name,
|
|
owner: session.user!.id,
|
|
people: body.data.people!,
|
|
level: body.data.level,
|
|
aspect: body.data.aspect,
|
|
notes: body.data.notes,
|
|
health: body.data.health,
|
|
mana: body.data.mana,
|
|
visibility: body.data.visibility,
|
|
thumbnail: body.data.thumbnail,
|
|
}).returning({ id: characterTable.id }).get().id;
|
|
|
|
if(body.data.leveling.length > 0) tx.insert(characterLevelingTable).values(body.data.leveling.map(e => ({ character: id, level: e[0], choice: e[1] }))).run();
|
|
|
|
const training = Object.entries(body.data.training).flatMap(e => e[1].map(_e => ({ character: id, stat: e[0] as MainStat, level: _e[0], choice: _e[1] })));
|
|
if(training.length > 0) tx.insert(characterTrainingTable).values(training).run();
|
|
|
|
const modifiers = Object.entries(body.data.modifiers).map((e) => ({ character: id, modifier: e[0] as MainStat, value: e[1] }));
|
|
if(modifiers.length > 0) tx.insert(characterModifiersTable).values(modifiers).run();
|
|
|
|
if(body.data.spells.length > 0) tx.insert(characterSpellsTable).values(body.data.spells.map(e => ({ character: id, value: e }))).run();
|
|
|
|
const abilities = Object.entries(body.data.abilities).map(e => ({ character: id, ability: e[0] as Ability, value: e[1][0], max: e[1][1] }));
|
|
if(abilities.length > 0) tx.insert(characterAbilitiesTable).values(abilities).run();
|
|
|
|
return id;
|
|
});
|
|
|
|
setResponseStatus(e, 201);
|
|
return id;
|
|
}
|
|
catch(_e)
|
|
{
|
|
console.error(_e);
|
|
|
|
setResponseStatus(e, 500);
|
|
return;
|
|
}
|
|
}); |