Files
lst_v3/backend/datamart/getDatamart.route.ts
Blake Matthes 24af3ca403 fix(datamart): somereason it stopped working.. and added download types
there was a weird issue with the req.query that cause nothing to pull and make the excel files
lag..... now excel macros are using the csv pull from here and added in the xlsx to download to bc
why not makes it easier for later  and can have bbuttons for every thing in lst too :D
2026-06-15 17:16:00 -05:00

90 lines
1.9 KiB
TypeScript

import { Router } from "express";
import * as XLSX from "xlsx";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { runDatamartQuery } from "./datamart.controller.js";
const r = Router();
type Options = {
name: string;
value: string;
format: string;
};
r.get("/:name", async (req, res) => {
const { name } = req.params;
const options = { ...req.query } as Options;
const dataRan = await runDatamartQuery({ name, options });
if (!dataRan.success) {
return apiReturn(res, {
success: false,
level: "error",
module: "datamart",
subModule: "query",
message: dataRan.message,
status: 500,
});
}
// XLSX Export
if (options.format?.toLowerCase() === "xlsx") {
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.json_to_sheet(dataRan.data);
XLSX.utils.book_append_sheet(wb, ws, name);
const buffer = XLSX.write(wb, {
type: "buffer",
bookType: "xlsx",
});
res.setHeader(
"Content-Type",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
);
res.setHeader("Content-Disposition", `attachment; filename="${name}.xlsx"`);
return res.send(buffer);
}
// CSV Export
if (options.format?.toLowerCase() === "csv") {
const rows = dataRan.data as any;
if (!rows.length) {
return res.status(200).send("");
}
const headers = Object.keys(rows[0]);
const csv = [
headers.join(","),
...rows.map((row: any) =>
headers
.map((h) => `"${String(row[h] ?? "").replace(/"/g, '""')}"`)
.join(","),
),
].join("\r\n");
res.setHeader("Content-Type", "text/csv");
res.setHeader("Content-Disposition", `attachment; filename="${name}.csv"`);
return res.send(csv);
}
return apiReturn(res, {
success: dataRan.success,
level: "info",
module: "datamart",
subModule: "query",
message: dataRan.message,
data: dataRan.data,
status: 200,
});
});
export default r;