import { FastifyInstance } from "fastify" import { asc, desc } from "drizzle-orm" import { sortData } from "../utils/sort" // Schema imports import { accounts, units,countrys } from "../../db/schema" const TABLE_MAP: Record = { accounts, units, countrys, } export default async function resourceRoutesSpecial(server: FastifyInstance) { server.get("/resource-special/:resource", async (req, reply) => { try { if (!req.user?.tenant_id) { return reply.code(400).send({ error: "No tenant selected" }) } const { resource } = req.params as { resource: string } // ❌ Wenn falsche Ressource if (!TABLE_MAP[resource]) { return reply.code(400).send({ error: "Invalid special resource" }) } const table = TABLE_MAP[resource] const { select, sort, asc: ascQuery } = req.query as { select?: string sort?: string asc?: string } // --------------------------------------- // 📌 SELECT: wir ignorieren select string (wie Supabase) // Drizzle kann kein dynamisches Select aus String! // Wir geben IMMER alle Spalten zurück → kompatibel zum Frontend // --------------------------------------- let query = server.db.select().from(table) // --------------------------------------- // 📌 Sortierung // --------------------------------------- if (sort) { const col = (table as any)[sort] if (col) { //@ts-ignore query = ascQuery === "true" ? query.orderBy(asc(col)) : query.orderBy(desc(col)) } } const data = await query // Falls sort clientseitig wie früher notwendig ist: const sorted = sortData( data, sort, ascQuery === "true" ) return sorted } catch (err) { console.error(err) return reply.code(500).send({ error: "Internal Server Error" }) } }) }