0
votes

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'],
      '[email protected]'
    );
    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 })
});
1
The part const users = getAllUsers(); if (error) { … can't workBergi
yes , I am aware .. it's why I asked for a tip ...user762579
Have you tried my answer below?Bergi
yes sorry I did not catch up the 2 comments ... see mine ..user762579

1 Answers

0
votes

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.