UNPKG

json-helpers

Version:

JSON stringify/parser managing 'undefined, Date and Buffer.

84 lines 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JSONReplacerInstanceOfImpl = void 0; const json_parser_1 = require("./json-parser"); function getObjectClass(constructor) { if (typeof constructor === 'function') { if (constructor.name) { return constructor.name; } const str = constructor.toString(); if (str.charAt(0) == '[') { return str.subst(8, str.length - 1); } else { const arr = str.match(/function\s*(\w+)/); if (arr && arr.length == 2) { return arr[1]; } } } return null; } class JSONReplacerSetup { constructor(replacer) { this.objectType = replacer.objectType; this.objectConstructor = replacer.objectConstructor; this.serialize = replacer.serialize; this.objectClass = getObjectClass(this.objectConstructor); } toJSON(obj) { return { type: this.objectType, data: this.serialize(obj) }; } } class JSONReplacerInstanceOfImpl { constructor() { this._jsonReplacerSetupsMap = new Map(); this._replacer = this._replacer.bind(this); } replacer(replacer) { const setup = new JSONReplacerSetup(replacer); if (replacer.serialize) { this._jsonReplacerSetupsMap.set(setup.objectClass, setup); } else { this._jsonReplacerSetupsMap.delete(setup.objectClass); } } _replacer(key, value) { if (typeof key === 'undefined') { return json_parser_1.ToJSONConstants.JSON_TOKEN_UNDEFINED; } if ((typeof value === 'object') && value && value.constructor) { const objectClass = getObjectClass(value.constructor); if (objectClass) { const format = this._jsonReplacerSetupsMap.get(objectClass); if (format) { return format.toJSON(value); } } } return value; } _replacerChain(replacer, key, value) { if (typeof key === 'undefined') { return json_parser_1.ToJSONConstants.JSON_TOKEN_UNDEFINED; } if (value && value.constructor) { const objectClass = getObjectClass(value.constructor); if (objectClass) { const format = this._jsonReplacerSetupsMap.get(objectClass); if (format) { return format.toJSON(value); } } } return replacer(key, value); } stringify(value, replacer, space) { const replacerCb = replacer ? this._replacerChain.bind(this, replacer) : this._replacer; return JSON.stringify(value, replacerCb, space); } } exports.JSONReplacerInstanceOfImpl = JSONReplacerInstanceOfImpl; //# sourceMappingURL=json-replacer-instanceof-impl.js.map