Initial commit
This commit is contained in:
@@ -0,0 +1,582 @@
|
||||
const express = require('express');
|
||||
const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCharacterAccess } = require('../middleware/characterAccess');
|
||||
const {
|
||||
computeCharacterSheet,
|
||||
computeWeaponStats,
|
||||
getClassSaveProficiencies,
|
||||
getClassSpellcastingAbility,
|
||||
ABILITIES,
|
||||
} = require('../game/calculations');
|
||||
const {
|
||||
rollDie,
|
||||
rollAbilityScore,
|
||||
speciesChoicesForRoll,
|
||||
classChoicesForRoll,
|
||||
MOTIVATION_TABLE,
|
||||
} = require('../game/buildFlow');
|
||||
const { SKILLS } = require('../game/data/skills');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
async function loadFullCharacter(id) {
|
||||
return prisma.character.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
skillProficiencies: true,
|
||||
saveProficiencies: true,
|
||||
inventoryItems: true,
|
||||
weapons: { include: { weapon: true } },
|
||||
spells: { include: { spell: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function serializeCharacter(character) {
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
return {
|
||||
id: character.id,
|
||||
campaignId: character.campaignId,
|
||||
userId: character.userId,
|
||||
createdById: character.createdById,
|
||||
name: character.name,
|
||||
species: character.species,
|
||||
characterClass: character.characterClass,
|
||||
level: character.level,
|
||||
xp: character.xp,
|
||||
motivation: character.motivation,
|
||||
halfElfBonusAbility1: character.halfElfBonusAbility1,
|
||||
halfElfBonusAbility2: character.halfElfBonusAbility2,
|
||||
rolledScores: {
|
||||
STR: character.strScore,
|
||||
DEX: character.dexScore,
|
||||
CON: character.conScore,
|
||||
INT: character.intScore,
|
||||
WIS: character.wisScore,
|
||||
CHA: character.chaScore,
|
||||
},
|
||||
currentHp: character.currentHp,
|
||||
tempHp: character.tempHp,
|
||||
armorBonus: character.armorBonus,
|
||||
specialAbilities: character.specialAbilities,
|
||||
gold: character.gold,
|
||||
buildStage: character.buildStage,
|
||||
buildState: character.buildStage === 'COMPLETE' ? null : character.buildState,
|
||||
skillProficiencies: character.skillProficiencies,
|
||||
saveProficiencies: character.saveProficiencies,
|
||||
inventoryItems: character.inventoryItems,
|
||||
weapons: character.weapons,
|
||||
spells: character.spells,
|
||||
sheet: character.buildStage === 'COMPLETE' ? sheet : null,
|
||||
};
|
||||
}
|
||||
|
||||
router.get('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
res.json({ character: serializeCharacter(character) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const patchCharacterSchema = z.object({
|
||||
name: z.string().min(1).max(80).optional(),
|
||||
currentHp: z.number().int().optional(),
|
||||
tempHp: z.number().int().min(0).optional(),
|
||||
armorBonus: z.number().int().min(0).optional(),
|
||||
speedOverride: z.number().int().min(0).nullable().optional(),
|
||||
specialAbilities: z.string().max(4000).nullable().optional(),
|
||||
gold: z.number().int().min(0).optional(),
|
||||
level: z.number().int().min(1).max(20).optional(),
|
||||
xp: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = patchCharacterSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const updated = await prisma.character.update({ where: { id: req.character.id }, data: parsed.data });
|
||||
const full = await loadFullCharacter(updated.id);
|
||||
const payload = serializeCharacter(full);
|
||||
|
||||
req.app.get('io').to(`campaign:${updated.campaignId}`).emit('character:updated', { character: payload });
|
||||
res.json({ character: payload });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
await prisma.character.delete({ where: { id: req.character.id } });
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Roll-Your-Character build flow — docs/ROLL_YOUR_CHARACTER.md
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
const stage = character.buildStage;
|
||||
const buildState = { ...(character.buildState || {}) };
|
||||
|
||||
if (stage === 'ROLLING_SPECIES') {
|
||||
const roll = rollDie(6);
|
||||
buildState.speciesRoll = roll;
|
||||
buildState.speciesChoices = speciesChoicesForRoll(roll);
|
||||
delete buildState.species;
|
||||
delete buildState.halfElfBonusAbilities;
|
||||
} else if (stage === 'ROLLING_CLASS') {
|
||||
const alreadyRolled = buildState.classChoices && buildState.classChoices.type !== 'reroll';
|
||||
if (alreadyRolled) {
|
||||
return res.status(400).json({ error: 'Class die already rolled for this character — submit a choice, or reroll if the current roll allows it.' });
|
||||
}
|
||||
const roll = rollDie(8);
|
||||
buildState.classRoll = roll;
|
||||
buildState.classChoices = classChoicesForRoll(roll);
|
||||
delete buildState.characterClass;
|
||||
} else if (stage === 'ROLLING_MOTIVATION') {
|
||||
const roll = rollDie(6);
|
||||
buildState.motivationRoll = roll;
|
||||
buildState.motivationText = MOTIVATION_TABLE[roll];
|
||||
} else if (stage === 'ASSIGNING_SCORES') {
|
||||
if (buildState.abilityRolls) {
|
||||
return res.status(400).json({ error: 'Ability scores were already rolled for this character.' });
|
||||
}
|
||||
buildState.abilityRolls = Array.from({ length: 6 }, () => rollAbilityScore());
|
||||
} else {
|
||||
return res.status(400).json({ error: `No die roll is required at the "${stage}" step.` });
|
||||
}
|
||||
|
||||
const updated = await prisma.character.update({ where: { id: character.id }, data: { buildState } });
|
||||
res.json({ buildStage: updated.buildStage, buildState: updated.buildState });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const HALF_ELF_ELIGIBLE_ABILITIES = ABILITIES.filter((a) => a !== 'CHA');
|
||||
|
||||
const chooseSchemas = {
|
||||
ROLLING_SPECIES: z.object({
|
||||
species: z.string(),
|
||||
halfElfBonusAbilities: z.array(z.enum(HALF_ELF_ELIGIBLE_ABILITIES)).length(2).optional(),
|
||||
}),
|
||||
ROLLING_CLASS: z.object({ characterClass: z.string() }),
|
||||
ROLLING_MOTIVATION: z.object({ motivation: z.string().max(500).optional() }),
|
||||
ASSIGNING_SCORES: z.object({
|
||||
assignments: z.object({
|
||||
STR: z.number().int().min(0).max(5),
|
||||
DEX: z.number().int().min(0).max(5),
|
||||
CON: z.number().int().min(0).max(5),
|
||||
INT: z.number().int().min(0).max(5),
|
||||
WIS: z.number().int().min(0).max(5),
|
||||
CHA: z.number().int().min(0).max(5),
|
||||
}),
|
||||
}),
|
||||
ASSIGNING_PROFICIENCIES: z.object({
|
||||
skillProficiencies: z.array(
|
||||
z.object({
|
||||
skill: z.enum(Object.keys(SKILLS)),
|
||||
proficient: z.boolean().default(true),
|
||||
expertise: z.boolean().default(false),
|
||||
})
|
||||
),
|
||||
}),
|
||||
CHOOSING_EQUIPMENT: z.object({
|
||||
weaponIds: z.array(z.string()).default([]),
|
||||
spellIds: z.array(z.string()).default([]),
|
||||
}),
|
||||
};
|
||||
|
||||
const STAGE_ORDER = [
|
||||
'ROLLING_SPECIES',
|
||||
'ROLLING_CLASS',
|
||||
'ROLLING_MOTIVATION',
|
||||
'ASSIGNING_SCORES',
|
||||
'ASSIGNING_PROFICIENCIES',
|
||||
'CHOOSING_EQUIPMENT',
|
||||
'COMPLETE',
|
||||
];
|
||||
|
||||
function nextStage(current) {
|
||||
const idx = STAGE_ORDER.indexOf(current);
|
||||
return STAGE_ORDER[idx + 1];
|
||||
}
|
||||
|
||||
router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
const stage = character.buildStage;
|
||||
const schema = chooseSchemas[stage];
|
||||
if (!schema) return res.status(400).json({ error: `No choice is expected at the "${stage}" step.` });
|
||||
|
||||
const parsed = schema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const buildState = { ...(character.buildState || {}) };
|
||||
let advanceTo = nextStage(stage);
|
||||
|
||||
if (stage === 'ROLLING_SPECIES') {
|
||||
const choices = buildState.speciesChoices;
|
||||
if (!choices) return res.status(400).json({ error: 'Roll for species before choosing one.' });
|
||||
const { species, halfElfBonusAbilities } = parsed.data;
|
||||
if (choices.type !== 'wildcard' && !choices.options.includes(species)) {
|
||||
return res.status(400).json({ error: `${species} was not offered by this roll.` });
|
||||
}
|
||||
if (species === 'HALF_ELF') {
|
||||
if (!halfElfBonusAbilities) {
|
||||
return res.status(400).json({ error: 'Half-Elf requires choosing two abilities (other than CHA) for the +1/+1 bonus.' });
|
||||
}
|
||||
if (new Set(halfElfBonusAbilities).size !== 2) {
|
||||
return res.status(400).json({ error: 'The two Half-Elf bonus abilities must be different.' });
|
||||
}
|
||||
buildState.halfElfBonusAbilities = halfElfBonusAbilities;
|
||||
} else {
|
||||
delete buildState.halfElfBonusAbilities;
|
||||
}
|
||||
buildState.species = species;
|
||||
} else if (stage === 'ROLLING_CLASS') {
|
||||
const choices = buildState.classChoices;
|
||||
if (!choices || choices.type === 'reroll') {
|
||||
return res.status(400).json({ error: 'Roll for class before choosing one.' });
|
||||
}
|
||||
const { characterClass } = parsed.data;
|
||||
if (choices.type !== 'wildcard' && !choices.options.includes(characterClass)) {
|
||||
return res.status(400).json({ error: `${characterClass} was not offered by this roll.` });
|
||||
}
|
||||
buildState.characterClass = characterClass;
|
||||
if (req.campaign.skipMotivationRoll) {
|
||||
advanceTo = 'ASSIGNING_SCORES';
|
||||
buildState.motivationText = null;
|
||||
}
|
||||
} else if (stage === 'ROLLING_MOTIVATION') {
|
||||
if (!buildState.motivationRoll) return res.status(400).json({ error: 'Roll for motivation first.' });
|
||||
if (parsed.data.motivation) buildState.motivationText = parsed.data.motivation;
|
||||
} else if (stage === 'ASSIGNING_SCORES') {
|
||||
if (!buildState.abilityRolls) return res.status(400).json({ error: 'Roll ability scores first.' });
|
||||
const { assignments } = parsed.data;
|
||||
const usedIndexes = Object.values(assignments);
|
||||
const uniqueIndexes = new Set(usedIndexes);
|
||||
if (uniqueIndexes.size !== 6 || Math.max(...usedIndexes) > 5) {
|
||||
return res.status(400).json({ error: 'Each of the 6 rolled scores must be assigned to exactly one ability.' });
|
||||
}
|
||||
buildState.abilityAssignments = assignments;
|
||||
} else if (stage === 'ASSIGNING_PROFICIENCIES') {
|
||||
buildState.skillProficiencies = parsed.data.skillProficiencies;
|
||||
} else if (stage === 'CHOOSING_EQUIPMENT') {
|
||||
const { weaponIds, spellIds } = parsed.data;
|
||||
const maxItems = req.campaign.startingItemCount;
|
||||
const maxSpells = req.campaign.startingSpellCount;
|
||||
if (weaponIds.length > maxItems) {
|
||||
return res.status(400).json({ error: `This campaign allows at most ${maxItems} starting item(s).` });
|
||||
}
|
||||
const hasSpellcasting = Boolean(getClassSpellcastingAbility(buildState.characterClass));
|
||||
if (spellIds.length > 0 && !hasSpellcasting) {
|
||||
return res.status(400).json({ error: 'This class has no spellcasting ability — it cannot pick starting spells.' });
|
||||
}
|
||||
if (spellIds.length > maxSpells) {
|
||||
return res.status(400).json({ error: `This campaign allows at most ${maxSpells} starting spell(s).` });
|
||||
}
|
||||
buildState.equipment = { weaponIds, spellIds };
|
||||
advanceTo = 'CHOOSING_EQUIPMENT'; // stay here; POST /build/finalize completes the character
|
||||
}
|
||||
|
||||
const updated = await prisma.character.update({
|
||||
where: { id: character.id },
|
||||
data: { buildState, buildStage: advanceTo },
|
||||
});
|
||||
res.json({ buildStage: updated.buildStage, buildState: updated.buildState });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
if (character.buildStage !== 'CHOOSING_EQUIPMENT') {
|
||||
return res.status(400).json({ error: `Character isn't ready to finalize (currently at "${character.buildStage}").` });
|
||||
}
|
||||
const bs = character.buildState || {};
|
||||
if (!bs.species || !bs.characterClass || !bs.abilityAssignments || !bs.equipment) {
|
||||
return res.status(400).json({ error: 'Build is incomplete — species, class, ability assignments, and equipment are all required.' });
|
||||
}
|
||||
|
||||
const rolledScores = {};
|
||||
for (const ability of ABILITIES) {
|
||||
const rollIndex = bs.abilityAssignments[ability];
|
||||
rolledScores[ability] = bs.abilityRolls[rollIndex].total;
|
||||
}
|
||||
|
||||
const [halfElfBonusAbility1, halfElfBonusAbility2] = bs.halfElfBonusAbilities || [null, null];
|
||||
const saveProfs = getClassSaveProficiencies(bs.characterClass);
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
await tx.characterSkillProficiency.deleteMany({ where: { characterId: character.id } });
|
||||
await tx.characterSaveProficiency.deleteMany({ where: { characterId: character.id } });
|
||||
|
||||
const updated = await tx.character.update({
|
||||
where: { id: character.id },
|
||||
data: {
|
||||
species: bs.species,
|
||||
characterClass: bs.characterClass,
|
||||
motivation: bs.motivationText || null,
|
||||
strScore: rolledScores.STR,
|
||||
dexScore: rolledScores.DEX,
|
||||
conScore: rolledScores.CON,
|
||||
intScore: rolledScores.INT,
|
||||
wisScore: rolledScores.WIS,
|
||||
chaScore: rolledScores.CHA,
|
||||
halfElfBonusAbility1,
|
||||
halfElfBonusAbility2,
|
||||
buildStage: 'COMPLETE',
|
||||
buildState: null,
|
||||
skillProficiencies: {
|
||||
create: (bs.skillProficiencies || []).map((sp) => ({
|
||||
skill: sp.skill,
|
||||
proficient: sp.proficient !== false,
|
||||
expertise: Boolean(sp.expertise),
|
||||
})),
|
||||
},
|
||||
saveProficiencies: {
|
||||
create: ABILITIES.map((ability) => ({ ability, proficient: saveProfs.includes(ability) })),
|
||||
},
|
||||
weapons: {
|
||||
create: (bs.equipment.weaponIds || []).map((weaponId) => ({ weaponId, quantity: 1, equipped: false })),
|
||||
},
|
||||
spells: {
|
||||
create: (bs.equipment.spellIds || []).map((spellId) => ({ spellId, prepared: false })),
|
||||
},
|
||||
},
|
||||
include: { skillProficiencies: true, saveProficiencies: true },
|
||||
});
|
||||
|
||||
const sheet = computeCharacterSheet(updated, updated.skillProficiencies, updated.saveProficiencies);
|
||||
const finalized = await tx.character.update({
|
||||
where: { id: character.id },
|
||||
data: { currentHp: sheet.hp.max },
|
||||
});
|
||||
return finalized;
|
||||
});
|
||||
|
||||
const full = await loadFullCharacter(result.id);
|
||||
const payload = serializeCharacter(full);
|
||||
req.app.get('io').to(`campaign:${result.campaignId}`).emit('character:created', { character: payload });
|
||||
res.json({ character: payload });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Quick Stats — combat-context panel (docs/GAME_RULES_REFERENCE.md)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
if (character.buildStage !== 'COMPLETE') {
|
||||
return res.status(400).json({ error: 'Character build is not finished yet.' });
|
||||
}
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
|
||||
const weapons = character.weapons.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
weaponId: cw.weaponId,
|
||||
name: cw.weapon.name,
|
||||
equipped: cw.equipped,
|
||||
quantity: cw.quantity,
|
||||
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true),
|
||||
}));
|
||||
|
||||
res.json({
|
||||
quickStats: {
|
||||
name: character.name,
|
||||
currentHp: character.currentHp,
|
||||
maxHp: sheet.hp.max,
|
||||
tempHp: character.tempHp,
|
||||
armorClass: sheet.armorClass,
|
||||
initiative: sheet.initiative,
|
||||
speed: sheet.speed,
|
||||
proficiencyBonus: sheet.proficiencyBonus,
|
||||
spellcasting: sheet.spellcasting,
|
||||
specialAbilities: character.specialAbilities,
|
||||
weapons,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Weapons assigned to this character
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/weapons', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ weaponId: z.string(), quantity: z.number().int().min(1).default(1) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const weapon = await prisma.weapon.findUnique({ where: { id: parsed.data.weaponId } });
|
||||
if (!weapon || weapon.campaignId !== req.character.campaignId) {
|
||||
return res.status(400).json({ error: 'That weapon is not part of this campaign.' });
|
||||
}
|
||||
|
||||
const characterWeapon = await prisma.characterWeapon.upsert({
|
||||
where: { characterId_weaponId: { characterId: req.character.id, weaponId: parsed.data.weaponId } },
|
||||
create: { characterId: req.character.id, weaponId: parsed.data.weaponId, quantity: parsed.data.quantity },
|
||||
update: { quantity: { increment: parsed.data.quantity } },
|
||||
include: { weapon: true },
|
||||
});
|
||||
res.status(201).json({ characterWeapon });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/weapons/:weaponId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z
|
||||
.object({ quantity: z.number().int().min(0).optional(), equipped: z.boolean().optional() })
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const characterWeapon = await prisma.characterWeapon.update({
|
||||
where: { characterId_weaponId: { characterId: req.character.id, weaponId: req.params.weaponId } },
|
||||
data: parsed.data,
|
||||
include: { weapon: true },
|
||||
});
|
||||
res.json({ characterWeapon });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Inventory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/inventory', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z
|
||||
.object({
|
||||
name: z.string().min(1).max(120),
|
||||
description: z.string().max(2000).optional().nullable(),
|
||||
quantity: z.number().int().min(1).default(1),
|
||||
equipped: z.boolean().default(false),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const item = await prisma.inventoryItem.create({ data: { ...parsed.data, characterId: req.character.id } });
|
||||
res.status(201).json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/inventory/:itemId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z
|
||||
.object({
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
description: z.string().max(2000).nullable().optional(),
|
||||
quantity: z.number().int().min(0).optional(),
|
||||
equipped: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const item = await prisma.inventoryItem.update({ where: { id: req.params.itemId }, data: parsed.data });
|
||||
res.json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/inventory/:itemId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
await prisma.inventoryItem.delete({ where: { id: req.params.itemId } });
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spells known by this character
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/spells', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ spellId: z.string(), prepared: z.boolean().default(false) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const spell = await prisma.spell.findUnique({ where: { id: parsed.data.spellId } });
|
||||
if (!spell || spell.campaignId !== req.character.campaignId) {
|
||||
return res.status(400).json({ error: 'That spell is not part of this campaign.' });
|
||||
}
|
||||
|
||||
const characterSpell = await prisma.characterSpell.upsert({
|
||||
where: { characterId_spellId: { characterId: req.character.id, spellId: parsed.data.spellId } },
|
||||
create: { characterId: req.character.id, spellId: parsed.data.spellId, prepared: parsed.data.prepared },
|
||||
update: { prepared: parsed.data.prepared },
|
||||
include: { spell: true },
|
||||
});
|
||||
res.status(201).json({ characterSpell });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/spells/:spellId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ prepared: z.boolean() }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const characterSpell = await prisma.characterSpell.update({
|
||||
where: { characterId_spellId: { characterId: req.character.id, spellId: req.params.spellId } },
|
||||
data: parsed.data,
|
||||
include: { spell: true },
|
||||
});
|
||||
res.json({ characterSpell });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Notes about this character
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/notes', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const notes = await prisma.note.findMany({
|
||||
where: {
|
||||
characterId: req.character.id,
|
||||
...(req.isDM ? {} : { OR: [{ visibility: 'SHARED' }, { authorId: req.user.id }] }),
|
||||
},
|
||||
include: { author: { select: { displayName: true } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
res.json({ notes });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user