我有一个存储在Firebase中的数据库,并希望使用'functions'来检查数据库中的记录是否为> n天。我明白了 的onChange() JavaScript中的函数可以为我实现这一点。谢谢!
答案 0 :(得分:0)
在我的项目中,我们经常使用这种模式。使用onChange()检测更改,然后使用辅助函数检查更改是否发生在特定字段中。此助手函数例如称为checkIfChangedHappenedToAtLeastOneOfProvidedPaths
,您可以通过提供检查路径来使用它,例如:checkIfChangedHappenedToAtLeastOneOfProvidedPaths(change.before.data(), change.after.data(), ['daysOld'])
checkIfChangedHappenedToAtLeastOneOfProvidedPaths
使用2个辅助函数来实现此目的(difference
& getDifferenceCombine
)。让我知道你的想法,这是代码(在打字稿中):
<强> checkIfChangedHappenedToAtLeastOneOfProvidedPaths 强>
/**
* The purpose of this function is to analyze the change between two objects.
* If a change happened to the prvoided path(s), return true, otherwise false,
* Usecase: Use this function if you only care about change at a certain path.
* Example: Run only update function if change happened to "stripe" object, at groups
* @export
* @param {*} oldObject
* @param {*} newObject
* @param {string[]} pathsToCheck
* @returns {boolean}
*/
export function checkIfChangedHappenedToAtLeastOneOfProvidedPaths(oldObject: object, newObject: object, pathsToCheck: string[]): boolean {
const combinedChanges = getDifferenceCombine(oldObject, newObject);
const flatObject = flat(combinedChanges);
let changeHappened = false;
pathsToCheck.forEach((path) => {
const inFlatObject = flatObject[path] != null;
const inCombinedObject = get(combinedChanges, path, null) != null;
if (inFlatObject || inCombinedObject) {
changeHappened = true;
}
});
return changeHappened;
}
帮助程序功能
export function difference(object: any, base: any): any {
return transform(object, (result, value, key) => {
if (base == null || object == null) {
return;
}
if (!isEqual(value, base[key])) {
result[key] = isObject(value) && isObject(base[key]) ? difference(value, base[key]) : value;
}
});
}
export function getDifferenceCombine(oldObject: object, newObject: object): object {
const diffObject = difference(newObject, oldObject);
const diffObject2 = difference(oldObject, newObject);
return {...diffObject, ...diffObject2};
}
答案 1 :(得分:-1)
由于所有内容都是实时更新的,因此如果要监视此特定字段,可以查询该字段。例如,假设您有一个子节点“ createdAt”,其值为Firebase.ServerValue.TIMESTAMP。
var n = 1452508000000; //random timestamp in milliseconds,
//since this is how firebase saves a server value timestamp or
//this can be Date.now() if you convert your createdAt value
//to whatever date format you prefer.
var ref = firebase.database().ref('path/to/your/data');
ref.orderByChild("createdAt").startAt(n).on("child_added", function(snapshot) {
console.log(snapshot.key);
//will list all keys that were created on or after the timestamp value
});
https://firebase.google.com/docs/reference/js/firebase.database.Query#startAt