UNPKG

@alinex/datastore

Version:

Read, work and write data structures from and to differents locations and formats.

59 lines 1.82 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.format = exports.parse = void 0; const path_1 = require("path"); const debug_1 = require("debug"); const toml = require("@iarna/toml"); const debug = debug_1.default('datastore:format:toml'); function cast(obj) { if (typeof obj !== 'object') return obj; let num = 0; let isArray = true; Object.keys(obj).forEach(k => { if (k !== `${num++}`) isArray = false; }); if (isArray) obj = Object.keys(obj).map(k => obj[k]); return obj; } function preformat(obj) { if (Array.isArray(obj)) { let hasObjects = true; let num = 0; const conv = {}; obj.forEach((e) => { if (typeof e !== 'object') hasObjects = false; conv[num++] = e; }); if (hasObjects) obj = conv; } 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(toml.parse(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(toml.stringify(preformat(Object.assign({}, data))))); }; exports.format = format; //# sourceMappingURL=toml.js.map