我正在尝试从另一个云函数调用云函数“startTimer”,并在调用函数“startTimer”时包含数据
例如,在我的客户端,很容易调用函数“startTimer”并通过编写以下(颤振代码)来包含数据:
HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('startTimer');
callable.call({"gameId": MyFirebase.gameId});
然后,我可以通过执行以下操作在我的云函数“startTimer”中检索数据:
exports.startTimer = functions.https.onCall(async (data, context) => {
const gameId = data.gameId;
我如何才能在另一个云函数中调用函数“startTimer”并包含数据 (gameId)?此外,我将如何做到这一点,以便像上面的代码片段(data.gameId)那样完全格式化/结构化数据? 我试过这样的事情,但它不起作用:
fetch("https://{LOCATION}-{PROJECT-ID}.cloudfunctions.net/startTimer", {
method: "POST",
body: JSON.stringify({"gameId": gameId}),)};
“fetch”来自
const fetch = require("node-fetch");
我对 javascript/typescript 还是很陌生,所以非常感谢任何帮助/参考:) 在此先感谢您!
答案 0 :(得分:0)
我可以看到两种可能性:
正如您将在 doc 中读到的,“Cloud Functions 的 https.onCall
触发器是一个 HTTPS 触发器具有特定格式的请求和响应。” >
所以你可以从另一个云函数调用可调用的云函数,例如Axios 或 fetch。
您可以在一个函数中重构业务逻辑,从两个云函数调用该函数:现有的可调用云函数或 a Pub/Sub triggered Cloud Function。类似以下内容,具有异步业务逻辑和 async/await 的使用:
exports.startTimer = functions.https.onCall(async (data, context) => {
try {
const gameId = data.gameId;
const result = await asyncBusinessLogic(gameId);
return { result: result }
} catch (error) {
// ...
}
});
exports.startTimerByPubSubScheduler = functions.pubsub.topic('start-timer').onPublish((message) => {
try {
const gameId = message.json.gameId;
await asyncBusinessLogic(gameId);
return null;
} catch (error) {
// ...
return null;
}
});
async function asyncBusinessLogic(gameId) {
const result = await anAsynchronousJob(gameId);
return result;
}
答案 1 :(得分:0)
除了@Renaud 之外,您还可以使用 Google Cloud Tasks 来调用您的 HTTP 函数。这样做的主要好处是您可以从第一个函数返回响应,而无需等待第二个函数的完成。这是一件小事,但我发现它在很多情况下都有帮助。
您可以将任何数据传递给您可能需要的 GCloud 任务主体,这样您就不必再次从第二个函数调用数据库。
exports.firstFunctions = functions.https.onCall(async (data, context) => {
// Functions logic
await addCloudTask(/*params*/)
//Return the response
})
const addCloudTask = async (queue, url, method, inSeconds, body) => {
const project = "<project-id>"
const location = "us-central1"
const parent = gCloudClient.queuePath(project, location, queue)
const [response] = await gCloudClient.createTask({
parent,
task: {
httpRequest: {
httpMethod: method,
url,
body: Buffer.from(JSON.stringify({body})).toString("base64"),
headers: {
"Content-Type": "application/json"
}
},
scheduleTime: {
seconds: inSeconds + (Date.now() / 1000)
}
}
});
return
}
您还可以传递 inSeconds
参数为回调添加任何延迟。