import { getInjection } from "@/di/container"; import db from "@/prisma/db"; import { AuthenticationError, UnauthenticatedError } from "@/src/entities/errors/auth"; import { InputParseError } from "@/src/entities/errors/common"; export async function getAvailableYears() { const instrumentationService = getInjection('IInstrumentationService'); return await instrumentationService.instrumentServerAction( 'Available Years', { recordResponse: true }, async () => { try { const years = await db.crimes.findMany({ select: { year: true, }, distinct: ["year"], orderBy: { year: "asc", }, }) return years.map((year) => year.year); } catch (err) { if (err instanceof InputParseError) { // return { // error: err.message, // }; throw new InputParseError(err.message); } if (err instanceof AuthenticationError) { // return { // error: 'User not found.', // }; throw new AuthenticationError('There was an error with the credentials. Please try again or contact support.'); } const crashReporterService = getInjection('ICrashReporterService'); crashReporterService.report(err); // return { // error: // 'An error happened. The developers have been notified. Please try again later.', // }; throw new Error('An error happened. The developers have been notified. Please try again later.'); } } ); } // Fetch districts with their geographic data and crime rates for the specified year export async function fetchDistricts(year: number) { const instrumentationService = getInjection('IInstrumentationService'); return await instrumentationService.instrumentServerAction( 'Fetch Districts', { recordResponse: true }, async () => { try { const districts = await db.districts.findMany({ include: { geographics: true, crimes: { where: { year: year, }, }, cities: { select: { name: true, }, }, }, }) // Transform the data for the map const geoData = districts.map((district) => { const crimeData = district.crimes[0] || null return { id: district.id, name: district.name, cityName: district.cities?.name || "Unknown City", polygon: district.geographics?.polygon || null, crimeRate: crimeData?.rate || "no_data", crimeCount: crimeData?.number_of_crime || 0, year: year, } }) return geoData } catch (err) { if (err instanceof InputParseError) { // return { // error: err.message, // }; throw new InputParseError(err.message); } if (err instanceof AuthenticationError) { // return { // error: 'User not found.', // }; throw new AuthenticationError('There was an error with the credentials. Please try again or contact support.'); } const crashReporterService = getInjection('ICrashReporterService'); crashReporterService.report(err); // return { // error: // 'An error happened. The developers have been notified. Please try again later.', // }; throw new Error('An error happened. The developers have been notified. Please try again later.'); } } ); }