0

I am currently experimenting Google Firebase functions to access Google APIs. It's running fine, but I am a little bit lost in trying to manage the errors that could be detected ...

In the .HTTPS getGoogleUsers functions , I would like to return an HTTP status code ( 200 or error code ) , and the data ( or error message )

As far as I can see , I can get errors:

  • from the connect() function ( 500: Internal server error or 401 Unauthorized )

  • from the listUsers() function ( 500: Internal server error or 400 Bad Request )

Am I totally or partially wrong ? what should be my strategy in this case ? thanks for feedback ..

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const {google} = require('googleapis');
const KEY = require('./service-key.json');

 // Create JSON Web Token Client
 function connect () {
  return new Promise((resolve, reject) => {
    const jwtClient = new google.auth.JWT(
      KEY.client_email,
      null,
      KEY.private_key,
      ['https://www.googleapis.com/auth/admin.directory.user'],
      'adminuser@mydomain.com'
    );
    jwtClient.authorize((err) => {
      if(err) {
        reject(err);
      } else {
        resolve(jwtClient);
      }
    });
  });
}

function listUsers (client) {
  return new Promise((resolve, reject) => {
    google.admin('directory_v1').users.list({
      auth: client,
      domain: 'mydomain.com',
    }, (err, response) => {
      if (err) {
        reject(err);
      }
      resolve(response.data.users);
    });
  });
}

function getAllUsers () {
  connect()
    .then(client => {
      return listUsers(client);
    })
    .catch(error => {
      return error;
    })
}
exports.getGoogleUsers = functions.https.onRequest((req, res) => {
  const users = getAllUsers();
  if (error) {
     status = error.status;
     data = error.message;
  } else {
    status = 200;
    data = users;
  }
  res.send({ status: status, datas: data })
});
J. Pichardo
  • 3,077
  • 21
  • 37

1 Answers1

0

I think you are looking for

function getAllUsers () {
  return connect().then(listUsers);
//^^^^^^
}

exports.getGoogleUsers = functions.https.onRequest((req, res) => {
  getAllUsers().then(users => {
    return {status: 200, datas: users};
  }, error => {
    return {status: error.status, datas: error.message};
  }).then(response => {
    res.send(response);
  });
});

This uses the .then(…, …) method with two callbacks to distinguish between success and error case, and to wait for the result of the promise.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • yes ,good point .. however I get a lint error in libe : getAllUsers().then(users => {... 53:3 error Expected catch() or return promise/catch-or-return –  May 16 '18 at 16:44
  • If any of the three callbacks (especially `res.send`) throws an error, it'll cause an unhandled rejection. You can add another `.catch(console.error)` at the end if you want. – Bergi May 16 '18 at 17:34