typescript-libraries
Version:
To install this library, run:
115 lines (114 loc) • 3.37 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSLogClass = TSLogClass;
exports.TSLogMethod = TSLogMethod;
exports.TSLogProperty = TSLogProperty;
exports.TSLog = TSLog;
require("reflect-metadata");
/**
* Log instance of a class
*
* @example @TSLogClass
*
* @param target
* @constructor
*/
function TSLogClass(target) {
var original = target;
function construct(constructor, args) {
var c = function () {
return constructor.apply(this, args);
};
c.prototype = constructor.prototype;
return new c();
}
var f = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
console.log("[TSLogClass::".concat(original['name'], "] is created"));
return construct(original, args);
};
f.prototype = original.prototype;
return f;
}
/**
* Log and measure performance of a function
*
* @example @TSLogMethod
*
* @param target
* @param key
* @param descriptor
* @constructor
*/
function TSLogMethod(target, key, descriptor) {
if (descriptor) {
var method_1 = descriptor.value;
descriptor.value = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var measure = function () { return exports.performance ? exports.performance.now() : +new Date(); }, start = measure(), params = args.map(function (a) { return JSON.stringify(a); }).join(), result = method_1.apply(this, args);
console.log("[TSLogMethod::".concat(key, "] (").concat(params, ") => ").concat(JSON.stringify(result, null, 2)));
console.log("[TSLogMethod::".concat(key, "] stats: ").concat((measure() - start).toFixed(2), " ms"));
return result;
};
return descriptor;
}
}
/**
* Log property state
*
* @example @TSLogProperty
*
* @param target
* @param key
* @constructor
*/
function TSLogProperty(target, key) {
var v = target[key];
var t = Reflect.getMetadata('design:type', target, key);
var getter = function () {
console.log("[TSLogProperty::Get:".concat(t.name, "] ").concat(key, " => ").concat(JSON.stringify(v, null, 2)));
return v;
};
var setter = function (nv) {
console.log("[TSLogProperty::Set:".concat(t.name, "] ").concat(key, " => ").concat(JSON.stringify(nv, null, 2)));
v = nv;
};
if (delete target[key]) {
Object.defineProperty(target, key, {
get: getter, set: setter, enumerable: true, configurable: true
});
}
}
/**
* Log factory that automatically detect kind signature
*
* @example @TSLog
*
* @param args
* @constructor
*/
function TSLog() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
switch (args.length) {
case 3:
if (typeof args[2] === 'undefined') {
return TSLogProperty.apply(this, args);
}
return TSLogMethod.apply(this, args);
case 2:
return TSLogProperty.apply(this, args);
case 1:
return TSLogClass.apply(this, args);
default:
throw new Error('Not a valid decorator');
}
}