ro-*_*age 27 javascript node.js firebase google-cloud-platform google-cloud-functions
我正在使用云功能在免费火花层上调用另一个云功能.
是否有一种特殊的方式来调用另一个云功能?或者您只是使用标准的http请求?
我试过直接调用其他函数:
exports.purchaseTicket = functions.https.onRequest((req, res) => {
fetch('https://us-central1-functions-****.cloudfunctions.net/validate')
.then(response => response.json())
.then(json => res.status(201).json(json))
})
Run Code Online (Sandbox Code Playgroud)
但是我得到了错误
FetchError:请求 https:// us-central1-functions-****.cloudfunctions.net/validate failed,reason:getaddrinfo ENOTFOUND us-central1-functions - *****.cloudfunctions.net us-central1-functions -*****cloudfunctions.net:443
哪个听起来像firebase阻止连接,尽管它是谷歌拥有的,因此它不应该被锁定
Spark计划仅允许对Google拥有的服务的出站网络请求.
如何使用云功能调用另一个云功能?
Dou*_*son 19
您无需通过全新的HTTPS调用来解决调用某些共享功能的麻烦.您可以简单地将代码的常见位抽象为一个由任一个调用的常规javascript函数.例如,您可以像这样修改模板helloWorld函数:
var functions = require('firebase-functions');
exports.helloWorld = functions.https.onRequest((request, response) => {
common(response)
})
exports.helloWorld2 = functions.https.onRequest((request, response) => {
common(response)
})
function common(response) {
response.send("Hello from a regular old function!");
}
Run Code Online (Sandbox Code Playgroud)
这两个函数将完全相同,但具有不同的端点.
要回答这个问题,你可以做一个 https 请求来调用另一个云函数:
export const callCloudFunction = async (functionName: string, data: {} = {}) => {
let url = `https://us-central1-${config.firebase.projectId}.cloudfunctions.net/${functionName}`
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ data }),
})
}
Run Code Online (Sandbox Code Playgroud)
(请注意,我们使用 npm 包“node-fetch”作为我们的 fetch 实现。)
然后简单地调用它:
callCloudFunction('search', { query: 'yo' })
Run Code Online (Sandbox Code Playgroud)
这样做是有正当理由的。我们用它每分钟 ping 我们的搜索云功能并保持它运行。这大大降低了每年几美元的响应延迟。
通过包含授权令牌,可以通过 HTTP 调用另一个 Google Cloud Function。它需要一个主要的 HTTP 请求来计算令牌,然后在调用要运行的实际 Google Cloud 函数时使用该令牌。
https://cloud.google.com/functions/docs/securing/authenticating#function-to-function
const {get} = require('axios');
// TODO(developer): set these values
const REGION = 'us-central1';
const PROJECT_ID = 'my-project-id';
const RECEIVING_FUNCTION = 'myFunction';
// Constants for setting up metadata server request
// See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
const functionURL = `https://${REGION}-${PROJECT_ID}.cloudfunctions.net/${RECEIVING_FUNCTION}`;
const metadataServerURL =
'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=';
const tokenUrl = metadataServerURL + functionURL;
exports.callingFunction = async (req, res) => {
// Fetch the token
const tokenResponse = await get(tokenUrl, {
headers: {
'Metadata-Flavor': 'Google',
},
});
const token = tokenResponse.data;
// Provide the token in the request to the receiving function
try {
const functionResponse = await get(functionURL, {
headers: {Authorization: `bearer ${token}`},
});
res.status(200).send(functionResponse.data);
} catch (err) {
console.error(err);
res.status(500).send('An error occurred! See logs for more details.');
}
};
Run Code Online (Sandbox Code Playgroud)
尽管问题标签和其他答案与javascript有关,但我想分享python示例,因为它反映了问题中提到的标题和身份验证方面。
Google Cloud Function 提供了REST API 接口,包括可以在另一个 Cloud Function 中使用的调用方法。尽管文档中提到使用 Google 提供的客户端库,但 Python 上的 Cloud Function 仍然没有。
相反,您需要使用通用的 Google API 客户端库。[这是蟒蛇一个]。3
使用这种方法的主要困难可能是对身份验证过程的理解。通常,您需要提供两件事来构建客户端服务: 凭据和作用域。
获取凭据的最简单方法是在应用程序默认凭据 (ADC) 库上进行中继。有关此的正确文档是:
获取范围的位置是每个 REST API 函数文档页面。像,OAuth 范围:https://www.googleapis.com/auth/cloud-platform
调用 'hello-world' 云函数的完整代码示例如下。运行前:
from googleapiclient.discovery import build
from googleapiclient.discovery_cache.base import Cache
import google.auth
import pprint as pp
def get_cloud_function_api_service():
class MemoryCache(Cache):
_CACHE = {}
def get(self, url):
return MemoryCache._CACHE.get(url)
def set(self, url, content):
MemoryCache._CACHE[url] = content
scopes = ['https://www.googleapis.com/auth/cloud-platform']
# If the environment variable GOOGLE_APPLICATION_CREDENTIALS is set,
# ADC uses the service account file that the variable points to.
#
# If the environment variable GOOGLE_APPLICATION_CREDENTIALS isn't set,
# ADC uses the default service account that Compute Engine, Google Kubernetes Engine, App Engine, Cloud Run,
# and Cloud Functions provide
#
# see more on https://cloud.google.com/docs/authentication/production
credentials, project_id = google.auth.default(scopes)
service = build('cloudfunctions', 'v1', credentials=credentials, cache=MemoryCache())
return service
google_api_service = get_cloud_function_api_service()
name = 'projects/{project_id}/locations/us-central1/functions/function-1'
body = {
'data': '{ "message": "It is awesome, you are develop on Stack Overflow language!"}' # json passed as a string
}
result_call = google_api_service.projects().locations().functions().call(name=name, body=body).execute()
pp.pprint(result_call)
# expected out out is:
# {'executionId': '3h4c8cb1kwe2', 'result': 'It is awesome, you are develop on Stack Overflow language!'}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10233 次 |
| 最近记录: |