service-utilities
Version:
Utility Package for FIORI UI5
96 lines (84 loc) • 2.94 kB
JavaScript
/**
* @module ServiceFile
* @description Utility Set for easy File Import and Export
* @author jpanti
* @version 1.0.0
* @created 2025-08-01
* @lastModified 2025-08-01
* @license ISC
*/
sap.ui.define(["sap/ui/model/json/JSONModel"], (JSONModel) => {
"use strict";
return {
// Utilities ========================================
getAbsolutePath: (...path) => sap.ui.require.toUrl(path.join("/")),
// ==================================================
// Import and Export ================================
importFileJSON: (path) =>
new Promise(function (resolve, reject) {
const oModel = new JSONModel();
oModel.attachRequestCompleted(function () {
resolve(oModel.getData());
});
oModel.attachRequestFailed(function (oEvent) {
reject(new Error("Failed to load JSON from " + path));
});
oModel.loadData(path, null, true); // async = true
}),
importFileCSV: (path) => fetch(path).then((response) => response.text()),
exportFile: (fileName, raw) => {
const blob = new Blob([raw], { type: "text/csv;charset=utf-8;" });
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
return fileName;
},
// ==================================================
// Converters =======================================
rawToObjects(raw) {
var objects = [];
var headers = [];
if (!raw || raw.trim() === "") return { objects, headers };
const separatorLine = "\n";
const linesRaw = raw.split(separatorLine);
const separatorCol = ",";
linesRaw.forEach((lineRaw, i) => {
const object = {};
const lineData = lineRaw.split(separatorCol);
if (i === 0) {
lineData.forEach((header) => headers.push(header));
} else {
headers.forEach((header, j) => (object[header] = lineData[j]));
objects.push(object);
}
});
return { objects, headers };
},
ObjectsToRaw({ objects, headers }) {
if (!objects || !headers) return;
const separatorCol = ",";
const headersRaw = headers.join(separatorCol);
const linesRaw = [];
objects.forEach((object) => {
if (!!object) {
var lineRaw = [];
headers.forEach((header) => {
if (object.hasOwnProperty(header)) {
lineRaw.push(object[header]);
}
});
linesRaw.push(lineRaw);
}
});
const separatorLine = "\n";
const raw = [headersRaw, ...linesRaw].join(separatorLine);
return raw;
},
};
// ==================================================
});