I'm calling the google analytics API and trying to format the data I received from it on my server side before passing then to the front. Concretely I would like to use promise
, to apply a map
function on the response I have from the api call.
Here is my google analytics API call :
var datatable = function(req, res) {
// authorize the client (see code above)
authorize(function() {
// do the actual call to the google api
analytics.data.ga.get({
'auth': jwtClient,
'ids': VIEW_ID,
'metrics': 'ga:pageviews, ga:avgTimeOnPage',
'dimensions': 'ga:contentGroup1, ga:searchDestinationPage',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'sort': '-ga:pageviews',
}, function (err, response) {
if (err) {
// there was an error (unlikely, except you're trying to view a non-allowed view)
console.log(err);
return;
}
// send the data to the client (i.e. browser)
res.send(response.rows);
});
});
}
I would like to apply the following map function map( ([x, y, z]) => ({ x, y, z }) )
using a promise (I will have more transformation to apply later on). So I've tried something like this :
const formated_data = function(req, res) {
return datatable()
.then(function (response, error) {
return res.send(response.map( ([x, y, z]) => ({ x, y, z }) )
});}
I've tried various thing but most of the time I have the following error : Cannot read property 'then' of undefined
. From what I have understand I know that my api call doesn't return me a promise however I don't know how I should refactor it so it return me a promise.
I'm using express so at the end I need to export my data with module.export
:
module.exports = {
datatable
};
edit#1: I did read the answers from this post and many others and tried to apply some solutions. However I'm getting stuck with this Cannot read property 'then' of undefined
. I understand why (my api call doesn't return a promise) but I don't know how to solve my issue.