我目前正在尝试使用Google Firebase功能来访问Google API。它运行正常,但我在尝试管理可以检测到的错误时有点迷失......
在.HTTPS getGoogleUsers
函数中,我想返回HTTP状态代码(200或错误代码),以及数据(或错误消息)
据我所知,我可能会收到错误:
connect()
功能的(500:内部服务器错误或401未经授权)
listUsers()
功能的(500:内部服务器错误或400错误请求)
我完全或部分错了吗?在这种情况下我的策略应该是什么? 感谢您的反馈..
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 })
});
答案 0 :(得分:0)
我认为你在寻找
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);
});
});
这使用the .then(…, …)
method with two callbacks来区分成功和错误情况,并等待承诺的结果。