miniprogram-logger
Version:
It is used to log and gather statistics of users' behavior.
85 lines (84 loc) • 2.55 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var guid_1 = require("./guid");
/**
* 序列化字符串
* @param data paramter
*/
function stringify(data) {
return data && typeof data !== "string" && typeof data !== "number" ? JSON.stringify(data) : data;
}
exports.stringify = stringify;
/**
* 默认Log对象转换函数
* 自动添加蛇形命名
* 字段中注入`id`和`timestamp`
* @param data LogObject
*/
function logTransformFunction(data) {
if (typeof data === "object") {
Object.keys(data).reduce(function (acc, key) {
var snake = key.replace(/([A-Z]+)/g, function (m, x) {
return "_" + x.toLowerCase();
});
if (!(snake in acc)) {
acc[snake] = data[key];
}
return acc;
}, data);
if (!data.id) {
data.id = guid_1.guid();
}
if (!data.timestamp) {
data.timestamp = new Date().toISOString();
}
}
return data;
}
exports.logTransformFunction = logTransformFunction;
/**
* 上报封装
*/
var Reporter = /** @class */ (function () {
function Reporter(table, fields, context) {
this.TableName = table;
this.Fields = fields;
this.Context = context || {};
}
Reporter.prototype.report = function () {
if (arguments.length === 0) {
//@ts-ignore
console.error("report need 1 or more parameters");
return;
}
var data = Object.assign({}, this.Context);
if (arguments.length === 1 && typeof arguments[0] === "object") {
Object.assign(data, arguments[0]);
}
else {
var n = Math.min(this.Fields.length, arguments.length);
while (n-- > 0) {
data[this.Fields[n]] = arguments[n];
}
}
if (this.TransformFunction) {
this.TransformFunction(data);
}
Object.keys(data).forEach(function (key) { return (data[key] = stringify(data[key])); });
wx.reportAnalytics(this.TableName, data);
};
Reporter.prototype.setContext = function () {
if (arguments.length == 1) {
Object.assign(this.Context, arguments[0]);
}
else if (arguments[1] === undefined) {
delete this.Context[arguments[0]];
}
else {
this.Context[arguments[0]] = arguments[1];
}
return this;
};
return Reporter;
}());
exports.Reporter = Reporter;