Firebase Cloud Funtion调用多次触发



I使用firebase和create触发器侦听学生文档中的任何更改。如果学生文档发生更改,我会将任何更改推送到rest api。但是我的函数调用了多次。

波纹管是我的功能:

exports.triggerTimeStudent= functions.firestore
.document('users/{userId}/class/{classId}/students/{studentId}')
.onUpdate( (change, context) => {
const newValue = change.after.data();
const previousValue = change.before.data();
const {update_at: afterStatus} = newValue;
const {update_at: beforeStatus} = previousValue;
const {name: name} = newValue;
if (afterStatus !== beforeStatus) {
try {
var data = {
"student_name": name,
};
console.log(data);
console.log("Inside Rest API");
return rest.post("https://example.com/api/v1/student/add-by-name", {
...studentServiceRestOption, ...{
body:  JSON.stringify(data)
}
});
} catch (error) {
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.send(buildError({
code: errorCode.SYSTEM_ERROR,
message: error.message,
}))
}
}

我不知道为什么函数多次调用。我只想打电话。我的功能不正确。请帮助

根据设计,云函数可以被多次调用。由您来确保您的函数能够处理重试。

但是,您的错误可能源于update_at键的值。如果该键的值是对象,则===!==操作数不会产生正确的结果。您需要检查对象的"isEqual"或"equals"方法,或者使用第三方解决方案(如_.isEqual(。

下面,为了提高性能和易用性,我重构了您的代码。我无法识别您用于API调用的rest对象,因此我已将其替换为node-fetch

const fetch = require("node-fetch"); // see https://www.npmjs.com/package/node-fetch
// for object equality tests
// const isEqual = require("lodash.isequal");
const STUDENT_SERVICE_DEFAULT_OPTIONS = {
method: "post",
headers: {
"Content-Type": "application/json"
}
}
exports.triggerTimeStudent= functions.firestore
.document("users/{userId}/class/{classId}/students/{studentId}")
.onUpdate( (change, context) => {
const beforeStatus = change.before.get("update_at"); // accessed directly for performance
const afterStatus = change.after.get("update_at");
// If beforeStatus and afterStatus are
//  - string, boolean, int, etc.: use beforeStatus === afterStatus
//  - firestore.Timestamp objects: use beforeStatus.isEqual(afterStatus)
//  - custom objects: use isEqual(beforeStatus, afterStatus) from lodash/underscore packages
if (beforeStatus === afterStatus) {
console.log("Status unmodified. Ignored change.");
return;
}
const data = {
student_name: change.after.get("name")
}
console.log("Making API call...", { data });
const fetchOptions = {
...STUDENT_SERVICE_DEFAULT_OPTIONS,
body: JSON.stringify(data)
}
return fetch("https://example.com/api/v1/student/add-by-name", fetchOptions)
.then(response => {
if (!response.ok) { // see "Handling client and server errors" in "node-fetch" docs
throw new Error("Unexpected API response: " + response.statusText);
}
console.log("Successfully added student!");
})
.catch(error => console.error("Failed to add student!", { error, fetchOptions }));
});

注意:您可以在Firebase控制台中查看来自云功能的日志消息。

相关内容

  • 没有找到相关文章

最新更新