This commit is contained in:
2025-12-09 12:26:18 +01:00
parent 6d05001812
commit 641130e506

View File

@@ -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<string, any> = {
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;
});
}
})
}