mysql-sender.js 875 Bytes
const client = require('./mysql-client');
const log = require('debug')('mysql');
const _ = require('lodash');

function flattenMsg(m) {
    return Object.assign({}, m.tags, m.fields);
}

class MySqlSender {
    constructor(table, duration = 2000) {
        this.table = table;
        this.batchMessages = [];

        setInterval(() => {
            this._send();
        }, duration);
    }

    addMessage(msg) {
        if (msg) {
            this.batchMessages.push(msg);
        }
    }

    _send() {
        const len = this.batchMessages.length;

        if (len < 1) {
            log('batchMessage is empty');
            return;
        }

        const bulk = this.batchMessages.splice(0, len);

        for (let i of bulk) {
            log('insert $0', i);
            client(this.table).insert(flattenMsg(i));
        }

    }
}

module.exports = MySqlSender;