问题描述
我有两个云函数,一个调用另一个。但是我不希望这个云函数被第一个云函数之外的任何其他东西调用。我有什么办法可以确定它是由第一个云函数调用的吗?
export const fetchleaderboard = functions
.runWith(runtimeOptions)
.region("us-central1")
.https.onRequest(async (_,response) => {
try {
const repo = new leaderboardRepository(new FirestoreleaderboardProvider());
const count = await repo.readCount();
const toIterate = Math.ceil(count / 1000);
const requests = [];
for (let i = 0; i < toIterate; i++) {
const config = {
headers: {
"Content-Type": "application/json",},} as AxiosRequestConfig;
const URL = "myurl";
requests.push(axios.post(URL,JSON.stringify({ pageNumber: i }),config));
}
await Promise.all(requests);
} catch (error) {
functions.logger.error("fetchleaderboard: Error sending leaderboard",{ structuredData: true });
}
response.sendStatus(200);
});
export const sendleaderboard = functions
.runWith(runtimeOptions)
.region("us-central1")
.https.onRequest(async (request,response) => {
try {
const pageNumber = JSON.parse(request.body).pageNumber ?? 0;
console.log(pageNumber);
} catch (error) {
functions.logger.error("fetchleaderboard: Error sending leaderboard",{ structuredData: true });
}
response.sendStatus(200);
});
解决方法
一种解决方案是将 sendLeaderboard
云函数从 HTTPS 更改为 Pub/Sub 函数:“外部”用户/消费者将无法直接调用此云函数。
Pub/Sub Cloud Function 将遵循以下几行:
const { PubSub } = require('@google-cloud/pubsub');
// ...
exports.sendLeaderboard = functions.pubsub.topic('send-leaderboard').onPublish(async (message) => {
try {
const pageNumber = message.json.pageNumber ?? 0; // Potentially to be adapted! Convert JSON value to number??
// ...
// await ...
return null;
} catch (error) {
console.error(error);
return null;
}
});
在第一个 Cloud Functions 函数中,您将调用以下函数
async function publishMessage(messageConfig) {
const pubSubClient = new PubSub();
const topicName = messageConfig.topicName;
const pubSubPayload = messageConfig.pubSubPayload;
let dataBuffer = Buffer.from(JSON.stringify(pubSubPayload));
await pubSubClient.topic(topicName).publish(dataBuffer);
}
如下:
messageConfig = {
topicName: 'send-leaderboard',pubSubPayload: {
pageNumber: i,// ....
}
}
await publishMessage(messageConfig);
请注意,如有必要,您可以将 publishMessage(messageConfig);
推送到要传递给 await Promise.all()
的数组。