@alinex/datastore
Version:
Read, work and write data structures from and to differents locations and formats.
101 lines • 3.21 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 moment = require("moment");
const ini = require("ini");
const debug = debug_1.default('datastore:format:ini');
function cast(obj) {
// @ts-ignore
const defaultFallback = moment.createFromInputFallback;
// @ts-ignore
moment.createFromInputFallback = function (config) {
config._d = new Date(NaN);
};
if (typeof obj !== 'object')
return obj;
Object.keys(obj).forEach(key => {
if (typeof obj[key] == 'string') {
// string -> number
const n = Number(obj[key]);
if (!isNaN(n)) {
obj[key] = n;
}
else {
// string -> date
const d = moment(obj[key]);
if (d.isValid())
obj[key] = d.toDate();
}
}
else if (typeof obj[key] == 'object' && obj[key]) {
// go deeper
obj[key] = cast(obj[key]);
}
});
// object -> array
let num = 0;
let isArray = true;
Object.keys(obj).forEach(k => {
if (k !== `${num++}`)
isArray = false; // no array
});
if (isArray)
obj = Object.keys(obj).map(k => obj[k]);
// @ts-ignore
moment.createFromInputFallback = defaultFallback;
return obj;
}
function preformat(obj) {
if (typeof obj !== 'object')
return obj;
Object.keys(obj).forEach(key => {
if (obj[key] instanceof Date) {
// Date -> string
obj[key] = obj[key].toISOString();
}
else if (Array.isArray(obj[key])) {
// array of objects -> object of objects
let hasObjects = true;
let num = 0;
const conv = {};
obj[key].forEach((e) => {
if (typeof e !== 'object')
hasObjects = false;
conv[num++] = e;
});
if (hasObjects)
obj[key] = conv;
}
else if (typeof obj[key] == 'object' && obj[key]) {
// go deeper
obj[key] = preformat(Object.assign({}, obj[key]));
}
});
return obj;
}
const parse = function (parsedUri, buffer) {
if (!parsedUri.pathname)
return Promise.reject(`No pathname given in ${parsedUri.href}`);
const pathname = parsedUri.hash || path_1.basename(parsedUri.pathname);
debug(`parsing ${pathname}`);
try {
return Promise.resolve(cast(ini.decode(buffer.toString())));
}
catch (err) {
err.data = buffer.toString();
return Promise.reject(err);
}
;
};
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}`);
return Promise.resolve(Buffer.from(ini.encode(preformat(Object.assign({}, data)))));
};
exports.format = format;
//# sourceMappingURL=ini.js.map