UNPKG

@alinex/datastore

Version:

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

63 lines 2.16 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 moment = require("moment"); const CSON = require("cson-parser"); // @ts-ignore const coffee = require("coffeescript"); const debug = debug_1.default('datastore:format:coffee'); 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 -> date const d = moment(obj[key]); if (d.isValid()) obj[key] = d.toDate(); } else if (typeof obj[key] == 'object' && obj[key]) { // go deeper cast(obj[key]); } }); // @ts-ignore moment.createFromInputFallback = defaultFallback; 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}`); let text = buffer.toString(); try { text = 'module.exports =\n ' + text.replace(/\n/g, '\n '); // @ts-ignore let m = new module.constructor(); m._compile(coffee.compile(text), 'inline.coffee'); return Promise.resolve(cast(m.exports)); } catch (error) { error.data = buffer.toString(); return Promise.reject(error); } }; 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(CSON.stringify(data, null, 4))); }; exports.format = format; //# sourceMappingURL=coffee.js.map