Files
CPLv4.0/pages/api/cpl/updateKueSettingsDataAPIHandler.ts
Ismail Ali b9651a53a9 esLint
2025-06-26 22:56:20 +02:00

68 lines
1.9 KiB
TypeScript

// /pages/api/cpl/updateKueSettingsDataAPIHandler.ts
import path from "path";
import fs from "fs/promises";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { key, value, slot } = req.query;
if (
typeof key !== "string" ||
typeof value !== "string" ||
typeof slot !== "string"
) {
return res
.status(400)
.json({ error: "Missing or invalid key, value, or slot parameter." });
}
const mockFilePath = path.join(
process.cwd(),
"device-cgi-simulator/SERVICE/kabelueberwachungMockData.js"
);
try {
const fileContent = await fs.readFile(mockFilePath, "utf-8");
const regex = new RegExp(`(var\\s+${key}\\s*=\\s*\\[)([^\\]]+)(\\])`);
const match = fileContent.match(regex);
if (!match) {
return res
.status(404)
.json({ error: `Key "${key}" not found in mock data.` });
}
const values = match[2]
.split(",")
.map((v) => v.trim())
.filter((_, i) => i < 32); // Optional: auf maximale Länge beschränken
const needsQuoting = isNaN(Number(value)) && !/^["'].*["']$/.test(value);
values[Number(slot)] = needsQuoting ? `"${value}"` : value;
// Entferne leere Slots
while (values.length > 0 && values[values.length - 1] === "") {
values.pop();
}
// Ergänze fehlende Slots mit leerem String
while (values.length < 32) {
values.push('""'); // Leerstring mit Anführungszeichen
}
const newArray = `var ${key} = [\n ${values.join(", ")}\n]`;
const updated = fileContent.replace(regex, newArray);
await fs.writeFile(mockFilePath, updated, "utf-8");
return res.status(200).json({ success: true, key, slot, value });
} catch (error) {
console.error("Mock update failed:", error);
return res.status(500).json({ error: "Internal server error." });
}
}