Miniflexa
Miniflexa

Reputation: 91

Actions on Google V2 webhook external api acces

In Actions on Google V1 I could easily parse info to and back from the api with the webhook,

but V2 has a different aproach, It skipped request() functions and only process the conv.tell/conv.ask.

V1 code:

function helpIntent (app) {                                   
        request(API_URL, { json: true }, function (error, response, body) {
              console.log("nameIntent Response: " + JSON.stringify(response) + " | Body: " + body + " | Error: " + error);
              var msg = body.response;
              app.tell(msg);
        });                                                                  
}

V2 code:

app.intent('help', (conv) => {
      request(API_URL, { json: true }, function (error, response, body) {
           console.log("nameIntent Response: " + JSON.stringify(response) + " | Body: " + body + " | Error: " + error);
           var msg = body.response;
           conv.close(msg);
      })                                                                   
});

So how to make conv.close(msg) was called correctly in V2 code?

Upvotes: 2

Views: 647

Answers (1)

Prisoner
Prisoner

Reputation: 50731

The issue is that request is an asynchronous operation. With the latest version of the actions-on-google library, if you have an asynchronous call inside your handler, you must return a Promise. Otherwise, when the handler ends, the async function will still be pending, and the code that triggers the handler doesn't know this, so it will return a response immediately.

The easiest way to do this is to use the request-promise-native package instead of the request package. This might make your code look something like this:

app.intent('help', (conv) => {
  var rp = require('request-promise-native');

  var options = {
    uri: API_URL,
    json: true // Automatically parses the JSON string in the response
  };

  return rp(options)
    .then( response => {
      // The response will be a JSON object already. Do whatever with it.
      console.log( 'response:', JSON.stringify(response,null,1) );
      var value = response.msg;
      return conv.close( value );
    });
};

Upvotes: 4

Related Questions