summaryrefslogtreecommitdiff
path: root/lib/workers/historyUpdater.js
blob: df80e92da56aa205b56f9deccec0ae7e2221c1db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// external modules
var async = require('async');

// core
var config = require("../config.js");
var logger = require("../logger.js");
var models = require("../models");

process.on('message', function (data) {
    if (!data || !data.msg || data.msg !== 'update history' || !data.caches) return process.exit();
    var caches = data.caches;
    async.each(Object.keys(caches), function (key, callback) {
        var cache = caches[key];
        if (config.debug) logger.info("history updater found dirty history: " + key);
        var history = parseHistoryToArray(cache);
        finishUpdateHistory(key, history, function (err, count) {
            if (err) return callback(err, null);
            if (!count) return callback(null, null);
            process.send({
                msg: 'check',
                userid: key
            });
            return callback(null, null);
        });
    }, function (err) {
        if (err) logger.error('history updater error', err);
        process.exit();
    });
});

function finishUpdateHistory(userid, history, callback) {
    models.User.update({
        history: JSON.stringify(history)
    }, {
        where: {
            id: userid
        }
    }).then(function (count) {
        return callback(null, count);
    }).catch(function (err) {
        return callback(err, null);
    });
}

function parseHistoryToArray(history) {
    var _history = [];
    Object.keys(history).forEach(function (key) {
        var item = history[key];
        _history.push(item);
    });
    return _history;
}

function parseHistoryToObject(history) {
    var _history = {};
    for (var i = 0, l = history.length; i < l; i++) {
        var item = history[i];
        _history[item.id] = item;
    }
    return _history;
}

module.exports = {
    parseHistoryToArray: parseHistoryToArray,
    parseHistoryToObject: parseHistoryToObject
};