const amqp = require('amqplib');

const mysql = require('mysql');

const connection = mysql.createConnection({

 host: 'localhost',

 user: 'root',

 password: 'root@123',

 database: 'abc'

});


connection.connect((err) => {

 if (err) throw err;

 console.log('Connected to MySQL database');

});


connection.ping(err => {

 if (err) {

   console.log("Host is not reachable");

 }

 else {

    amqp.connect('amqp://guest:guest@localhost:5672/prakash').then((conn) => {

   return conn.createChannel().then((ch) => {

     const q = 'pk';

       ch.assertQueue(q, {

       durable: true,

   });

   

       return ch.consume(q, (msg) => {

         if (msg !== null) {

            msgArr = msg.content.toString();

            var obj = JSON.parse(msgArr);

            var data = {

             name: obj[0],

            address: obj[1]

            };

        

           connection.query('INSERT INTO subscriber (name, address) VALUES (?,?)', JSON.parse(msg.content.toString()) , (error, results, fields) => {

             if (error) throw error;

             console.log('Data inserted:', data);

             ch.ack(msg);

           });

          

         }

       });

   

    

   });

  

 }).catch((error) => {

   console.log('Error:', error);


    connection.end((err) => {

   if (err) throw err;

   console.log('Connection to MySQL database closed');

  

 });

  });


 }

})