UNPKG

@spare-technologies/spare-typescript-sdk

Version:
97 lines 2.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const typescript_json_serializer_1 = require("typescript-json-serializer"); const hash = tslib_1.__importStar(require("js-sha256")); const stringify = require('json-stable-stringify'); const serializer = new typescript_json_serializer_1.JsonSerializer({ errorCallback: typescript_json_serializer_1.logError, nullishPolicy: { undefined: 'remove', null: 'remove' } }); /** * Get json object */ Object.prototype.toJson = function () { return serializer.serialize(this); }; Object.prototype.toStableJson = function () { const ser = serializer.serialize(this); const json = removeNullProperties(ser); return stringify(json); }; /** * Get json string * @param pretty */ Object.prototype.toJsonString = function (pretty = false) { return this.getCleanJson(serializer.serialize(this), pretty); }; /** * Get sha256 digest */ Object.prototype.sha256 = function () { return hash.sha256(this.toJsonString(false)); }; /** * Get sha224 digest */ Object.prototype.sha224 = function () { return hash.sha224(this.toJsonString(false)); }; /** * Check if equal to object * @param object */ Object.prototype.isEqual = function (object) { return object.sha256() == this.sha256(); }; /** * Get clean json * @param jsonObject * @param pretty */ Object.prototype.getCleanJson = function (jsonObject, pretty) { const clone = JSON.parse(JSON.stringify(jsonObject)); for (const prop in clone) { if (clone.hasOwnProperty(prop)) { if (clone[prop] == null) { delete clone[prop]; } } } return pretty ? JSON.stringify(clone, Object.keys(clone).sort(), '\t') : JSON.stringify(clone, Object.keys(clone).sort()); }; function removeNullProperties(obj) { Object.keys(obj).forEach(key => { let value = obj[key]; let hasProperties = value && Object.keys(value).length > 0; if (value === null) { delete obj[key]; } if (Array.isArray(value)) { obj[key] = value.filter(function (el) { removeNullProperties(value); return el != null; }); stringify(obj[key]); } else if ((typeof value !== "string") && hasProperties) { removeNullProperties(value); } }); toString(obj); return obj; } function toString(o) { Object.keys(o).forEach(k => { if (typeof o[k] === 'object') { return toString(o[k]); } o[k] = '' + o[k]; }); return o; } //# sourceMappingURL=SerilizableExtension.js.map