Y
Y
YagoRkO2020-03-22 14:38:44
Asterisk
YagoRkO, 2020-03-22 14:38:44

How to collect data from two simultaneous events into one object in Nodejs?

Good day. I connect to Asterisk using the asterisk-ami-client library.
I monitor the queue for incoming calls and try to collect data from two different events into one object.
At the first AgentConnect event, I create a key-value in Redis with primary call data.
At the end of the call, the AgentComplete and Cdr events arrive at the same time and I need to collect data from them.
In these two events, the first thing I do is get the existing data from Redis, complete the object, and write back.
As a result, in both events I get an incomplete object, which is written to the database in the same form.
Before writing to the database, I check the object for completeness, but even here there is a mistake. How to collect data from two events into one object and write it down at the end of the assembly??
Apparently there is not enough programming skills or understanding of the algorithm. Enlighten please.

module.exports = function (AmiClientConn, AmiClient, redisClient, queue_list, queue_member_list, RestClient, settings) {
    const {promisify} = require("util");
    const fs = require("fs");
    let hmgetAsync = promisify(redisClient.hmget).bind(redisClient)
    let hmsetAsync = promisify(redisClient.hmset).bind(redisClient)

    AmiClientConn.then(() => {

        AmiClient.on('AgentConnect', async event => {
            console.warn(event.Event, event.Uniqueid);
            let call_obj = {
                calltime: '',
                number: event.CallerIDNum,
                queue: event.Queue,
                dialstatus: '',
                uniqid: event.Uniqueid,
                talktime: '',
                holdtime: event.HoldTime,
                reason: '',
                agnum: event.MemberName
            }
            let redis_agent_connect_obj_string = JSON.stringify(call_obj);
            console.warn(event.Event, event);

            let redis_result = await hmsetAsync(`agentconnect`, {[event.Uniqueid]: redis_agent_connect_obj_string})
            console.log('AgentConnectRedis', redis_result)

        });

        AmiClient.on('AgentComplete', async event => {
            let agent_connect_complete_data_string = await hmgetAsync(`agentconnect`, event.Uniqueid)

            if (agent_connect_complete_data_string[0] !== null) {
                let agent_connect_complete_data_obj = JSON.parse(agent_connect_complete_data_string[0]);
                console.log('ПОЛУЧИЛ ДАННЫЕ В AgentComplete', agent_connect_complete_data_obj)
                let redis_agent_complete_data_obj = {
                    ...agent_connect_complete_data_obj,
                    talktime: event.TalkTime,
                    reason: event.Reason
                };

                let redis_agent_complete_data_obj_string = JSON.stringify(redis_agent_complete_data_obj)
                let redis_result = await hmsetAsync(`agentconnect`, {[event.Uniqueid]: redis_agent_complete_data_obj_string})
                console.log('AgentCompleteRedis', redis_result);



                let last_redis_complite_check_string = await hmgetAsync(`agentconnect`, event.Uniqueid)
                let last_redis_complite_check_obj = JSON.parse(last_redis_complite_check_string);

                let rest_agent_complete_data_obj = {
                    data: {
                        ...last_redis_complite_check_obj
                    },
                    headers: {"Content-Type": "application/json"}
                };

                console.log('ОБЪЕКТ В AGENTCOMPLETE', last_redis_complite_check_obj)
                if (last_redis_complite_check_obj.calltime !== '') {
                    await RestClient.post(`${settings.serverUri}/callin/create`, rest_agent_complete_data_obj, function (data, response) {
                        console.log('СОЗДАНИЕ ЗАПИСИ В АГЕНТКОМПЛИТ', data);
                        fs.appendFile("call_logger.txt", `${JSON.stringify(data)}\n`, function (error) {
                            if (error) throw error; // если возникла ошибка
                            console.log("Асинхронная запись файла завершена.");
                        })
                    })
                }
            }
        });

        AmiClient.on('Cdr', async event => {setTimeout()
            let agent_connect_cdr_data_string = await hmgetAsync(`agentconnect`, event.UniqueID)

            if(agent_connect_cdr_data_string[0] !== null) {
                let agent_connect_cdr_data_obj = JSON.parse(agent_connect_cdr_data_string[0]);
                console.log('ПОЛУЧИЛ ДАННЫЕ В Cdr', agent_connect_cdr_data_obj)
                if(agent_connect_cdr_data_obj.calltime === '') {
                    let redis_agent_cdr_data_obj = {
                        ...agent_connect_cdr_data_obj,
                        calltime: event.StartTime,
                        dialstatus: event.Disposition
                    };

                    let redis_agent_cdr_data_obj_string = JSON.stringify(redis_agent_cdr_data_obj)
                    let redis_result = await hmsetAsync(`agentconnect`, {[event.UniqueID]: redis_agent_cdr_data_obj_string})
                    console.log('AgentCdrRedis', redis_result)

                    let last_redis_cdr_check_string = await hmgetAsync(`agentconnect`, event.UniqueID)
                    let last_redis_cdr_check_obj = JSON.parse(last_redis_cdr_check_string);

                    let rest_agent_cdr_data_obj = {
                        data: {
                            ...last_redis_cdr_check_obj
                        },
                        headers: {"Content-Type": "application/json"}
                    };

                    console.log('ОБЪЕКТ В CDR', last_redis_cdr_check_obj)
                    if (last_redis_cdr_check_obj.talktime !== '') {
                        await RestClient.post(`${settings.serverUri}/callin/create`, rest_agent_cdr_data_obj, function (data, response) {
                            console.log('СОЗДАНИЕ ЗАПИСИ В СДР', data);
                            fs.appendFile("call_logger.txt", `${JSON.stringify(data)}\n`, function (error) {
                                if (error) throw error; // если возникла ошибка
                                console.log("Асинхронная запись файла завершена.");
                            })
                        })
                    }
                }
            }
        });


    })
        .catch(error => console.log(error))
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2020-03-22
@Che603000

use promises https://learn.javascript.ru/promise

Promise.all(promis1, promis2) // разрешится когда сработает каждый из промисов
.then(datas=>{
  // здесь можно получить данные, преобразовать и записать в db
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question