perf-reporter.js 2.68 KB
var storage = require('./storage');
var reporter = require('./reporter');

var perfKey = '_perfLog';

var resourcePerf = require('./perf/resource'),
    timingPerf = require('./perf/timing');

var perfReporter = {
    init: function(debug) {
        this.debug = debug;
        this.dataList = [];
        this.isRunning = false;

        resourcePerf.init(this.debug);
        timingPerf.init(this.debug);

        this.report();

        var self = this;

        window.addEventListener && window.addEventListener('load', function() {
            setTimeout(function() {
                self.collect();
            }, 0);
        });
    },

    collect: function() {
        try {
            var timingPerfData = timingPerf.collect();
            var resourcePerfData = resourcePerf.collect();

            this.chunkWrite(timingPerfData);

            for (var i = 0; i < resourcePerfData.length; i++) {
                this.chunkWrite(resourcePerfData[i]);
            }
        } catch(e) {
            if (this.debug) {
                console.log(e);
            }
        }
    },

    getMeta: function() {
        return {
            pt: encodeURIComponent(window.location.href), // url
            u: reporter.getUid(),                         // uid
            ud: reporter.getUdid(),                       // udid
            rid: reporter.getReqId(),                     // reqId
            r: reporter.getRoute()                        // server route
        }
    },

    jsonConcat: function(object1, object2) {
        for (var key in object2) {
            object1[key] = object2[key];
        }
        return object1;
    },

    write: function(item) {
        this.jsonConcat(item, this.getMeta());

        var perfList = JSON.parse(storage(perfKey) || '[]');
        perfList.push(item);
        storage(perfKey, JSON.stringify(perfList));

        if (perfList.length >= 3) {
            this.report();
        }
    },

    report: function() {
        var self = this;
        var perfList = JSON.parse(storage(perfKey) || '[]');
        var perfStr = reporter.stringify(perfList);

        reporter.report(perfStr, function() {
            self.clear();
        });
    },

    clear: function() {
        storage(perfKey, '[]');
    },

    chunkWrite: function(item) {
        var self = this;
        this.dataList.push(item);

        if (this.isRunning) {
            return;
        }

        this.isRunning = true;

        function _write() {
            if (self.dataList.length === 0) {
                return
            }

            var data = self.dataList.shift();

            self.write(data);
            setTimeout(_write,  10);
        }

        _write();
    }
};

perfReporter.init();