Getting partial api data from firebase functions- actions-on-google - actions-on-google

When I try to access external API's for my google action from my webhook which is hosted on firebase functions, I am getting back only partial content. It stops getting the whole data provided by the api.
For example I tried getting data from wikipedia api using this code
var request = require('request');//required module
//inside the function
request({ method: 'GET',url:'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&explaintext=&exsectionformat=plain&redirects=&titles=11_September'},function (error, response, body)
{
if (!error && response.statusCode == 200)
{
console.log(body);
}
});
app.ask('data obtained');
Can anyone please help me out with this.
I am having a pay as you go firebase account that allows egress of data.

From just the code fragment, the problem is that you're replying to the user outside the callback from request(). This means that it is handled immediately and the function may end before the entire body has been received. Try something like this (I've also changed ask() to tell() since you're not prompting for another response here, and you shouldn't leave the microphone open.)
var request = require('request');//required module
//inside the function
request({ method: 'GET',url:'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&explaintext=&exsectionformat=plain&redirects=&titles=11_September'},function (error, response, body)
{
if (!error && response.statusCode == 200)
{
console.log(body);
app.tell('data obtained');
}
});

Related

How to handle api failure in gupshup bot http call

I am making a http call from the gupshup IDE bot as below.
function MessageHandler(context, event) {
if(event.message. == "postdata") {
var url = "https://abcserver.com/sm/postData";
var header = {"token":"ca916a68d94","Content-Type": "application/x-www-form-urlencoded"};
var param = "userName=John&phoneNumber=1123111111";
context.simplehttp.makePost(url,param,header);
}
function HttpResponseHandler(context, event) {
var result= JSON.parse(event.getresp);
if(result=="success")
context.sendResponse("We have successfully stored your data");
}
I need a way to handle the failure i.e if the url (https://abcserver.com/sm/postData) is not reachable then I don't get any callback, HttpResponseHandler is not called in this case and the bot stops abruptly. I need a way to know that the corresponding api request has failed.I tried using try catch but it doesn't work.
Any link to the correct documentation or code example is welcome.

How to know the response of a callback rest call protractor

I am running an automation script. We have a scenario where Java makes a callback REST call to UI. Below is the code where am doing httpGet to that URL. I want to know when the response comes. If it comes how to know that. I searched a lot I din't find a clear answer anywhere. Please give some hints!
http.get(siteUrl, function(response) {
var bodyString = '';
response.setEncoding('utf8');
response.on("data", function(chunk) {
bodyString += chunk;
});
response.on('end', function() {
defer.fulfill({
statusCode: response.statusCode,
bodyString: bodyString
});
});
}).on('error', function(e) {
defer.reject("Got http.get error: " + e.message);
});
//If we are sure that response has come, then extract it
httpGet("http://testurl").then(function(result) {
//alert('inside test automation');
console.log(result);
});
You can use the response detail whether success or fail with "response code", there are lots of way using interface as callback, using methods by checking response code, lots of network library available - volley, okhttp rest client etc...
help : response code detail
if(response.statusCode == 200) {
// do success work read response etc...
// you can call methods what you want if success happen
} else {
// you can check other status code too..
// call methods if api get fail.
}
Hope this would help
good luck.

Nuxt Axios Module read status code

I'm calling a Rest API that returns at least 2 success status codes .
A normal 200 OK and a 202 Accepted status code.
Both return a Content in the body.
If I execute in postman my calls I might get something like
Status code: 202 Accepted. With Body "Queued" or some other values
or
Status code: 200 OK. With Body "ValueOfSomeToken"
Making the call with axios in my nuxt app:
this.$axios.$get('/Controller/?id=1')
.then((response)=>{
if(response=='Queued'){
//Do something
}
else if (response=='Expired'){
//Do something
}
else{
//Do something
}
})
.catch((error)=>{
console.log(error);
});
..works, but I actually would like to get the status code (because 202 has other values for the body responses)
I have no idea how to read the status codes.
I tried using (response,code) =>... but code is then nothing.
You can use non $-prefixed functions like this.$axios.get() instead of this.$axios.$get() to get the full response
// Normal usage with axios
let { data } = await $axios.get('...'));
// Fetch Style
let data = await $axios.$get('...');
(source)
You can extract the status codes from the response object in axios
if you print the response object (as shown in below image) you can see the all the objects inside the response object. One among them is status object
response.status will give you the status code that is sent from the server
axios.get("http://localhost:3000/testing").then((response)=>{
console.log("response ",response);
if(response.status == 200){
//do something
}
else if(response.status == 202){
//do something
}
else if(response.status == 301){
//do something
}
}).catch((err)=>{
console.log("err11 ",err);
})
In the server side, you can explicitly send any status code using res.status() method, for more details refer this documentation
app.get('/testing',(req, res)=> {
res.status(202).send({"res" : "hi"});
});
Update:
By default, #nuxtjs/axios returns response.data in the .then((response))
The $axios.onResponse event will have access to the complete response object.
You need to setup an interceptor to intercept the $axios.onResponse event and modify the response object
Under plugin directory create a plugin, plugin/axios.js
Update the plugins section plugins : ['~/plugins/axios']
in nuxt.config.js
export default function ({ $axios, redirect }) {
$axios.onResponse(res=>{
console.log("onResponse ", res);
res.data.status = res.status;
return res;
})
}
In the res object in this interceptor you will have the all the values (as it is shown in my first screenshot). But this res object is not returned as it is, only res.data is returned to our program.
We can update contents inside res.data and then return the res object as shown in my program res.data.status = res.status; .
Now when axios returns res.data we will have access to res.data.status value in response object in the .then((response)) promise
You can access the status using response.status inside this.$axios
this.$axios.$get("url").then((response) =>{
console.log("status ",response.status);
}).catch((err) => {
console.log("res err ",err);
});

Asynchronous Request to Facebook API with Redux

I am using Redux and trying to make a call to Facebook API with their JS SDK. I've only ever used promises with Redux and so since the method FB.getLoginStatus just returns a simple JS object, I'm not sure how to ensure that the payload doesn't return undefined.
With redux-promise, you add it to the applyMiddleware(ReduxPromise)... and then it ensures nothing is returned until the promise resolves. But I don't know how to do that here.
I've also used async/await functions with React Native without an issue, but I tried using them here and for some reason the code still returns the payload, before the asynchronous request (await ...) is finished. So I tried working with redux-await, but couldn't get it to work.
export function getLoginStatus() {
var res = FB.getLoginStatus(function(res) {
console.log(res);
});
console.log("res ", res);
return {
type: GET_LOGIN_STATUS,
payload: res
}
}
Hm, things can get a little tricky as I've not used redux-promise. And I can't tell exactly what else you have tried. But this would be my first shot:
async function _getLoginStatus() {
var payload = new Promise( (resolve, fail) => {
FB.getLoginStatus((res)=>resolve(res));
});
return {
type: GET_LOGIN_STATUS,
payload: payload
}
}
// Last time I exported an async function I needed this HYMMV
export let getLoginStatus = _getLoginStatus;
And then elsewhere in the code:
import {getLoginStatus} from 'whatever.js';
var payloadResult = await getLoginStatus();

Intern test framework - Making a REST API call

I am trying to make a REST API call as below and once the call is complete, I want to print "Done".
But with the below example "Done" is getting printed even before the REST call is complete.
return this.remote
.then(function() {
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
})
.then(function() {
console.log("Done")
})
Am I missing something here? If this not the right way, could someone please let me know what the right way is.
Thanks.
For Leadfoot (the library that Intern uses to drive functional tests) to keep track of an asynchronous operation, asynchronous operations in then callbacks should return Promises (or thenables). Luckily, request returns a promise, so just do:
.then(function () {
return request('...', function (...) {
...
});
})