diff --git a/src/routes/resourcesSpecial.ts b/src/routes/resourcesSpecial.ts index 9fae6ac..18a30bc 100644 --- a/src/routes/resourcesSpecial.ts +++ b/src/routes/resourcesSpecial.ts @@ -1,34 +1,74 @@ -import {FastifyInstance} from "fastify"; -import {sortData} from "../utils/sort"; +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) { - // Liste + server.get("/resource-special/:resource", async (req, reply) => { - if (!req.user?.tenant_id) { - return reply.code(400).send({ error: "No tenant selected" }); + 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) { + 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 } - - const { resource } = req.params as { resource: string }; - - if(!["accounts","units","countrys"].includes(resource)) return reply.code(400).send({ error: "No corrected special resource selected" }); - - const {select, sort, asc } = req.query as { select?: string, sort?: string, asc?: string } - console.log(select, sort, asc) - - - const { data, error } = await server.supabase - .from(resource) - //@ts-ignore - .select(select || "*") - if (error) { - console.log(error) - return reply.code(400).send({ error: error.message }); + catch (err) { + console.error(err) + return reply.code(500).send({ error: "Internal Server Error" }) } - - // @ts-ignore - const sorted =sortData(data,sort,asc === "true" ? true : false) - - return sorted; - }); -} \ No newline at end of file + }) +}