我们正致力于开发采用Google Cloud Functions的基于微服务的架构 .
我们开发了一些函数,并希望实现一个发现服务 . 此发现服务将用于确定特定功能是否存在且是否可操作 .
服务发现本身就是一个 Cloud 功能 . 它向以下API发出休息请求,并使用函数模拟器和默认应用程序凭据成功进行本地开发 .
谷歌为此提供了一个API [https://cloud.google.com/functions/docs/reference/rest/v1beta2/projects.locations.functions/get][1]
部署到 生产环境 时,我们收到:{"code":401,"message":“请求缺少必需的身份验证凭据 . 预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据 . 请参阅https://developers.google.com/identity/sign-in/web/devconsole-project . ", " status ": " UNAUTHENTICATED”}}
Cloud 功能是无状态的,所以没有选择使用我能看到的服务帐户 . 如何验证 Cloud 函数以调用函数api以确定函数是否可用?
以下是我们在本地开发环境中完成此操作的方法:
var options = {
method: 'get',
uri: `https://cloudfunctions.googleapis.com/v1beta2/projects/${config.PROJECT_ID}/locations/${config.LOCATION_ID}/functions/${functionName}`
}
console.log (options.uri);
request(options, function (err, res, body) {
if (!err && res.status === 200) {
if(typeof res.body.httpsTrigger.url !== undefined) {
console.log('found a function');
return cb(false, res.body.httpsTrigger.url);
}
else {
console.log('no function found, looking for static content');
return cb(true, `Service doesn't exist, returned ${res.status}`)
}
}
else {
console.log('no function found, looking for static content');
return cb(true, `Service doesn't exist, returned ${res.status}`);
}
});
2 回答
您提到的API包含方法:projects.locations.functions.get,它需要以下OAuth范围之一:
您可以查看Authentication in HTTP Cloud Functions在线文档 .
所以我终于想出了如何做到这一点 . 这有点黑客:
下载服务帐户的JSON密钥文件 .
将JSON文件添加到Function源 .
安装google-auth-library NPM模块 .
修改使用google-auth-library中的客户端的请求
const = require('google-auth-library'); const client = auth.fromJSON(keys); client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; client.authorize() . then(function(){const url =
https://cloudfunctions.googleapis.com/v1beta2/projects/${config.PROJECT_ID}/locations/${config.LOCATION_ID}/functions/${functionName}
; client.request(,function(err,res){if(err){console.log(Error: ${err}
); return cb(true,Service, ${functionName} doesn't exist, returned ${res}
)} else {console.log(RESPONSE: ${JSON.stringify(res.data)}
); console.log(Found Service at ${res.data.httpsTrigger.url}
); return cb(false,res.data.httpsTrigger.url);}});});