jazzedge
7/11/2017 - 6:44 PM

Bot - Full Example: Synchronous remote file GET using promises

Bot - Full Example: Synchronous remote file GET using promises

'use strict';
// 01. Include required files
require('dotenv-extended').load();
var restify = require('restify'); 
var builder = require('botbuilder');

// 02. Setup Restify Server
var server = restify.createServer();

// 03. Configure listen for messages
server.listen(process.env.PORT || 3978, function() 
{
   console.log('%s listening to %s', server.name, server.url); 
});

// 04. Create chat bot
var connector = new builder.ChatConnector
 ({
     appId: process.env.MICROSOFT_APP_ID,
     appPassword: process.env.MICROSOFT_APP_PASSWORD
 });

// 05. Listen for messages
server.post('/api/messages', connector.listen());

// 06. Serve static files
server.get(/.*/, restify.serveStatic({
    directory: __dirname,
    'default': 'index.html'
}));


var html = 'HTML';

// 01. Root Dialog
var bot = new builder.UniversalBot(connector, [
    (session, args, next) => {
        session.send("Hello");
        next();
    },
    (session, args, next) =>{
        session.send("Going Async...");  
        session.beginDialog('async');    // Call the Asynchronous demo dialog that does an https: GET lookup
    }
]);

bot.dialog('async', [
    function (session, results, next) {
        session.sendTyping();           // Give a visual indication that the system is responding. Note: this disappears after a couple of seconds
        html = getContent('https://newapi.enfield.gov.uk/address-search/postcode/EN1%201AA')   // Make the GET call. This could take a while, or not.
        .then((html) => {               // Once a response is received, you enter into this section (or the catch section if there is an error)
            console.log('JSON', html);  // Display the result on the console to prove it's arrived. Then delay moving on for 20 seconds
            setTimeout(function() {     // Add a delay just to show that you don't go to the next step in the waterfall until this section is reached     
            session.send('Succeeding out of the async dialog...' + html);                  
                next();
            },20000); //Give it 20 seconds just to prove that next
        })
        .catch((err) => {
            console.error('OOPS:',err)
            session.send('Erroring out of the async dialog...');
        });    
    },  
    function(session, results)  
    {  
        session.endDialog('Now we are out!'); // You should arrive here 20 seconds after the data is shown on the console. = Synchronous GET !!!
    }  
]);  
 

function getContent(url) {
  // return new pending promise
  return new Promise((resolve, reject) => {
    // select http or https module, depending on reqested url
    const lib = url.startsWith('https') ? require('https') : require('http');
    const request = lib.get(url, (response) => {
      // handle http errors
      console.log("Response code:", response.statusCode);
      if (response.statusCode < 200 || response.statusCode > 299) {
         reject(new Error('Failed to load page, status code: ' + response.statusCode));
       }
      // temporary data holder
      const body = [];
      // on every content chunk, push it to the data array
      response.on('data', (chunk) => body.push(chunk));
      // we are done, resolve promise with those joined chunks
      response.on('end', () => resolve(body.join('')));
    });
    // handle connection errors of the request
    request.on('error', (err) => reject('Chips' + err))
    })
};