76 lines
2.3 KiB
TypeScript
76 lines
2.3 KiB
TypeScript
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) {
|
|
|
|
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: select-string wird in dieser Route bewusst ignoriert
|
|
// 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" })
|
|
}
|
|
})
|
|
}
|