history.js 1.05 KB
'use strict';

const MAX_HISTORY = 1000;

const redis = require('redis');

const config = require('komodo-sdk/config');
const logger = require('komodo-sdk/logger');

const redisClient = redis.createClient(config.redis || { host: '127.0.0.1' });

const REDIS_KEYWORD = `SHAKIR_SMS_HISTORY_${config.name||'SMS'}`;

function push(item) {
    redisClient.LPUSH(REDIS_KEYWORD, JSON.stringify(item), () => {
        redisClient.LTRIM(REDIS_KEYWORD, 0, MAX_HISTORY);
    });
}

function dump() {
    return new Promise((resolve) => {
        const result = [];

        redisClient.LRANGE(REDIS_KEYWORD, 0, -1, (err, reply) => {
            reply.forEach((el) => {
                try {
                    result.push(JSON.parse(el));
                } catch (e) {
                    logger.warn(`Error parsing JSON on redis history. ${e.toString()}`);
                }            
            });
            logger.info(`History fetched from redis with ${reply.length} items.`);

            resolve(result);
        });
    
    })
}

exports.push = push;
exports.dump = dump;