Send response back to client after google compute engine api call in node js

3/5/2018

I am trying to get the Kubernetes cluster details from google cloud using google cloud Kubernetes API for node js.

Below is the example i have found in google documentation.

var google = require('googleapis');
var container = google.container('v1');

authorize(function(authClient) {
  var request = {
     projectId: 'my-project-id',  
     zone: 'my-zone',  
     clusterId: 'my-cluster-id',  
     auth: authClient,
  };

  container.projects.zones.clusters.get(request, function(err, response){
    if (err) {
       console.error(err);
    return;
  }

// TODO: Change code below to process the `response` object and send the detail back to client.

  console.log(JSON.stringify(response, null, 2));
  });
});

function authorize(callback) {
   google.auth.getApplicationDefault(function(err, authClient) {
     if (err) {
       console.error('authentication failed: ', err);
       return;
   }
   if (authClient.createScopedRequired && authClient.createScopedRequired()) {
       var scopes = ['https://www.googleapis.com/auth/cloud-platform'];
       authClient = authClient.createScoped(scopes);
   }
   callback(authClient);
  });
}

As the google get API is asynchronous function, how can I return the response from API back to client.

-- p_nair
google-cloud-platform
google-compute-engine
kubernetes-container
node.js

1 Answer

3/6/2018

The question is what do you want to do with the data? It's not an issue of the API being asynchronous or not, this snippet of code should return in the console the same JSON you would get with this request:

GET https://container.googleapis.com/v1beta1/projects/[PROJECT ID]/locations/[ZONE]/clusters/[CLUSTER NAME]

The function and callback should take care of the fact that it's asynchronous.

-- Jordi Miralles
Source: StackOverflow