habits.andr33v.ru/server/api/village/index.get.ts

51 lines
1.3 KiB
TypeScript

import { getUserIdFromSession } from '../../utils/auth';
import { isCropGrown } from '../../utils/village';
import { CropType, VillageObjectType } from '@prisma/client';
// --- DTOs ---
interface VillageObjectDto {
id: number;
type: VillageObjectType;
x: number;
y: number;
cropType: CropType | null;
isGrown: boolean | null;
}
interface VillageDto {
objects: VillageObjectDto[];
}
// --- Handler ---
export default defineEventHandler(async (event): Promise<VillageDto> => {
const userId = await getUserIdFromSession(event);
let village = await prisma.village.findUnique({
where: { userId },
include: { objects: true },
});
// If the user has no village yet, create one automatically.
if (!village) {
village = await prisma.village.create({
data: { userId },
include: { objects: true },
});
}
// Map Prisma objects to clean DTOs, computing `isGrown`.
const objectDtos: VillageObjectDto[] = village.objects.map(obj => ({
id: obj.id,
type: obj.type,
x: obj.x,
y: obj.y,
cropType: obj.cropType,
isGrown: obj.type === 'FIELD' ? isCropGrown(obj.plantedAt, obj.cropType) : null,
}));
return {
objects: objectDtos,
};
});