这是(从 Angular 调用 Firebase 函数给出“错误请求”错误,但从 URL 调用可以正常工作)的后续问题,仅用于历史目的。
我编写了一个 Firebase 函数,但我错误地将其写为 HTTP 调用而不是可调用函数。我尝试重写该函数,但我对语法仍然有点困惑。我编写的函数返回 500 错误。谁能帮助我理解正确的方法并帮助我修复这个功能?
这个概念很简单。我有一个名为“quizzes”的集合,其中包含测验文档,我想按其 doc.id 返回给定的测验文档。这是功能代码:
// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const { logger } = require("firebase-functions");
const { onRequest } = require("firebase-functions/v2/https");
const { cors } = require("cors")({ origin: true });
// Dependencies for callable functions.
const { onCall, HttpsError } = require("firebase-functions/v2/https");
// The Firebase Admin SDK to access Firestore.
const { initializeApp, applicationDefault, cert } = require("firebase-admin/app");
const { getFirestore, Timestamp, FieldValue, Filter } = require("firebase-admin/firestore");
initializeApp();
const db = getFirestore();
exports.getQuizById = onCall(async (request, response) => {
const quizId = request.queryid;
if (!quizId) {
throw new HttpsError("invalid-argument", "The function must be called " +
"with one arguments \"id\" containing the id of the quiz to retrieve.");
}
try {
const quizDocref = db.collection("quizzes").doc(quizId);
const quizDoc = await quizDocref.get();
// If there is no document with the given ID, return 404
if (!quizDoc.exists) {
throw new HttpsError("invalid-id", "The id " + quizId + " did not match any existing documents. Verify the id on the server or emulator and try again.");
}
// If the document exists, return the data from the document
return quizDoc.data();
} catch (error) {
// If there is an error, log the error and return 500
throw new HttpsError("server-error", "Error: " + error);
}
});
我通过以下方式从客户端调用此函数:
import { Functions, httpsCallable } from '@angular/fire/functions';
private functions: Functions = inject(Functions);
constructor(private route: ActivatedRoute) {
// get the id fdrom the url
const id = this.route.snapshot.params['id'];
const getQuizById = httpsCallable(this.functions, 'getQuizById');
getQuizById({ id: 'ef8GwUuHt8X4XQJBIgZf' })
.then((result) => {
console.log(result);
});
}
传递给函数的
request
对象比您预期的更复杂。它包含的内容比客户端发送的有效负载要多得多。如文档中所述:
请求参数包含从客户端应用程序传递的数据以及身份验证状态等附加上下文。
使用 CallableRequest 的 API 文档 查找其中的所有内容。客户端发送的有效负载位于 data
属性中。如果您的客户像这样发送:
const getQuizById = httpsCallable(this.functions, 'getQuizById');
getQuizById({ id: 'ef8GwUuHt8X4XQJBIgZf' })
那么你的函数需要像这样接收它:
const quizId = request.data.id;
另请注意,没有 response
对象传递给函数。您应该将其从代码中删除。响应由您从函数返回的值决定 - 您无法控制它。