@alinex/datastore
Version:
Read, work and write data structures from and to differents locations and formats.
71 lines • 2.45 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.format = exports.parse = void 0;
const path_1 = require("path");
const debug_1 = require("debug");
const flat = require("flat");
const XLSX = require("xlsx");
const debug = debug_1.default("datastore:format:xlsx");
function toObject(arr, recordFormat) {
let res = recordFormat ? [] : {};
arr.forEach(row => {
if (recordFormat) {
res.push(flat.unflatten(row));
}
else {
res[row[0]] = row[1] === "" ? null : row[1];
}
});
return recordFormat ? res : flat.unflatten(res);
}
function toArray(obj) {
let res = [];
if (Array.isArray(obj)) {
Object.keys(obj).forEach(key => {
res.push(flat.flatten(obj[key]));
});
}
else {
obj = flat.flatten(obj);
Object.keys(obj).forEach(key => {
res.push([key, obj[key]]);
});
}
return res;
}
const parse = function (parsedUri, buffer, options) {
if (!parsedUri.pathname)
return Promise.reject(`No pathname given in ${parsedUri.href}`);
const pathname = parsedUri.hash || path_1.basename(parsedUri.pathname);
debug(`parsing ${pathname}`);
const wb = XLSX.read(buffer, { type: 'buffer', cellDates: true });
const ws = wb.Sheets[wb.SheetNames[0]];
const work = XLSX.utils.sheet_to_json(ws);
let colls = [];
work.forEach(row => {
if (colls.length < Object.keys(work[0]).length)
colls = Object.keys(work[0]);
});
work.forEach(row => {
colls.forEach(coll => {
if (typeof row[coll] == 'undefined')
row[coll] = null;
});
});
let recordFormat = (options && options.records) || Object.keys(work[0]).length > 2;
return Promise.resolve(toObject(work, recordFormat));
};
exports.parse = parse;
const format = function (parsedUri, data) {
if (!parsedUri.pathname)
return Promise.reject(`No pathname given in ${parsedUri.href}`);
const pathname = parsedUri.hash || path_1.basename(parsedUri.pathname);
debug(`formatting for ${pathname}`);
const list = toArray(data);
const ws = XLSX.utils.json_to_sheet(list);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Data");
return Promise.resolve(XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' }));
};
exports.format = format;
//# sourceMappingURL=xlsx.js.map