UNPKG

@szegedsw/lib-node

Version:

A little framework published by Szeged Software Zrt. in order to enhance api endpoint security and create reuseable code. Email module, Logging system, and much more. Further improvements are expected.

156 lines 6.32 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CsvHandler = void 0; const axios_1 = __importDefault(require("axios")); const csv_stringify_1 = __importDefault(require("csv-stringify")); const fs_1 = __importDefault(require("fs")); const path_1 = require("path"); const config_1 = require("../config/config"); const export_1 = require("../controller/export"); const request_1 = require("../express/request"); const logger_1 = require("../logger/logger"); class CsvHandler extends export_1.Controller { constructor(getSession) { super(); Object.defineProperty(this, "getSession", { enumerable: true, configurable: true, writable: true, value: getSession }); Object.defineProperty(this, "errors", { enumerable: true, configurable: true, writable: true, value: { "rows is not an array": { code: "unprocessableEntity", body: "Records are not provided in an array!" }, "Unexpected end of JSON input": { code: "notFound", body: "" }, "Request failed with status code 400": { code: "conflict", body: "Underlying controller received invalid input object!" }, "url not found": { code: "expectationFailed", body: "URL not found in the preprocess!" }, } }); Object.defineProperty(this, "get", { enumerable: true, configurable: true, writable: true, value: async (req, res) => { const { url, from, ...rest } = request_1.requestParams(req); let { to } = request_1.requestParams(req); if (from && !to) { to = -1; } // tslint:disable-next-line: max-line-length const queryParams = Object.entries(removeUndefined({ to, from, ...rest }, [])) .map((pair) => pair.map(encodeURIComponent).join("=")) .join("&"); // tslint:disable-next-line: max-line-length const response = await axios_1.default.get(`${config_1.env.nodeSsl ? "https" : "http"}://localhost:${config_1.env.nodePort}/${config_1.env.nodeApiName || "api"}${decodeURIComponent(url)}?${queryParams}`, { headers: { Cookie: req.headers.cookie }, }); const data = await this.preprocessData(url, response.data); const key = Object.keys(data).filter((value) => value !== "count")[0]; await this.generateCsv(req, key, data[key], async (path, error) => { if (error) { throw error; } res.download(path, (err) => { if (err) { logger_1.Logger.error(err); res.status(config_1.HttpCodes.internalError).json(err).end(); } else { fs_1.default.unlinkSync(path); } }); }); } }); } async preprocessData(url, data) { if (!url) { throw Error("url not found"); } return data; } async getLocale(lang) { // eslint-disable-next-line no-empty if (lang) { } // do nothing return "en-GB"; } async getTimeZone(country) { // eslint-disable-next-line no-empty if (country) { } // do nothing return "Europe/Budapest"; } async generateCsv(req, name, rows, callback) { if (!Array.isArray(rows)) { await callback("", new Error("rows is not an array")); return; } const { userId, lang, country } = this.getSession(req); const date = new Date(Date.now()).toISOString().split(" ").join("-").split(":").join("-").split(".").join("-"); const path = `${config_1.env.downloadDirectory + path_1.sep + userId}-${name}-${date}.csv`; const locale = await this.getLocale(lang); const timeZone = await this.getTimeZone(country); const convertDate = (value) => new Date(value).toLocaleString(locale, { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", hour12: false, minute: "2-digit", second: "2-digit", }); await this.convertData(lang, rows); csv_stringify_1.default(rows, { delimiter: ";", header: true, cast: { // number: (value) => `="${value}"`, string: (value) => { const isDate = new RegExp(/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/).test(value); // eslint-disable-next-line no-nested-ternary return isDate ? convertDate(value) : !Number.isNaN(Number(value)) ? `="${value}"` : value; }, date: convertDate, }, columns: await this.getColumns(lang, rows), }, (err, output) => { if (err) { logger_1.Logger.error(err); callback(path, err); } else { fs_1.default.writeFile(path, `\ufeff${output}`, { encoding: "utf8" }, (error) => { if (error) { logger_1.Logger.error(error); callback(path, error); } else { callback(path); } }); } }); } post(_req, _res) { throw new Error("Method not implemented."); } patch(_req, _res) { throw new Error("Method not implemented."); } put(_req, _res) { throw new Error("Method not implemented."); } delete(_req, _res) { throw new Error("Method not implemented."); } } exports.CsvHandler = CsvHandler; //# sourceMappingURL=csv-handler.js.map