|
7 | 7 | parseUrlQueryParams,
|
8 | 8 | } from "./helpers.js";
|
9 | 9 | import { resolve } from "path";
|
| 10 | +import { jsonToCSV } from "./helpers.js"; |
| 11 | +import { isPasswordValid } from "./auth.js"; |
10 | 12 |
|
11 | 13 | export const routes = {
|
12 | 14 | home(req, res) {
|
@@ -75,6 +77,53 @@ export const routes = {
|
75 | 77 | });
|
76 | 78 | },
|
77 | 79 |
|
| 80 | + downloadCenter(req, res) { |
| 81 | + const htmlPath = resolve(PROJECT_ROOT_PATH, "views", "download.html"); |
| 82 | + fs.readFile(htmlPath, function (err, data) { |
| 83 | + if (err) { |
| 84 | + res.writeHead(404); |
| 85 | + res.write("Errors: File not found"); |
| 86 | + return res.end(); |
| 87 | + } |
| 88 | + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); |
| 89 | + res.write(data); |
| 90 | + return res.end(); |
| 91 | + }); |
| 92 | + }, |
| 93 | + |
| 94 | + download(req, res){ |
| 95 | + let body = ""; |
| 96 | + req.on("data", (chunk) => { |
| 97 | + body += chunk.toString(); // convert Buffer to string |
| 98 | + }); |
| 99 | + |
| 100 | + req.on("end", async () => { |
| 101 | + let bodyJson = queryStringToJson(body); |
| 102 | + if(!bodyJson || !bodyJson['username'] || !bodyJson['password'] || !isPasswordValid(bodyJson['username'], bodyJson['password'])){ |
| 103 | + res.writeHead(404); |
| 104 | + res.write("Not Authorized"); |
| 105 | + return res.end(); |
| 106 | + } |
| 107 | + const jsonData = storage.get(); |
| 108 | + const format = bodyJson['format']; |
| 109 | + if(format && format==='json'){ |
| 110 | + // Set headers for JSON file download |
| 111 | + res.setHeader('Content-Disposition', 'attachment; filename=data.json'); |
| 112 | + res.setHeader('Content-Type', 'application/json'); |
| 113 | + // Convert JavaScript object to JSON string and send |
| 114 | + const jsonString = JSON.stringify(jsonData, null, 2); |
| 115 | + return res.end(jsonString); |
| 116 | + } |
| 117 | + // Send as csv format by default |
| 118 | + // Set headers for CSV file download |
| 119 | + res.setHeader('Content-Disposition', 'attachment; filename=data.csv'); |
| 120 | + res.setHeader('Content-Type', 'text/csv'); |
| 121 | + // Convert JavaScript object to CSV and send |
| 122 | + const csvString = jsonToCSV(jsonData); |
| 123 | + return res.end(csvString); |
| 124 | + }) |
| 125 | + }, |
| 126 | + |
78 | 127 | default(req, res) {
|
79 | 128 | res.writeHead(404);
|
80 | 129 | res.write("Path not found!");
|
|
0 commit comments