我是Firebase Cloud Functions的新手。 一定时间后,如何在实时数据库中自动删除消息?例如1分钟1天,等等。
我正在尝试使用此处提供的示例(https://github.com/firebase/functions-samples/tree/master/delete-old-child-nodes),并在使用firebase deploy命令后收到以下错误:
i deploying functions Running command: npm --prefix "$RESOURCE_DIR" run lint
functions@ lint /home/vitor/remove_msgs_teste/functions eslint .
/home/vitor/remove_msgs_teste/functions/index.js 29:111 error Parsing error: Unexpected token =>
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! functions@ lint: eslint . npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the functions@ lint script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in: npm ERR! /home/vitor/.npm/_logs/2019-04-15T12_51_56_231Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1
我的index.js:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 30000; // 30sec in milliseconds.
/**
* This database triggered function will check for child nodes that are older than the
* cut-off time. Each child needs to have a `timestamp` attribute.
*/
exports.deleteOldItems = functions.database.ref('/mensagens/{idone}/{idtwo}/{pushid}').onWrite(async (change) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = now - CUT_OFF_TIME;
const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
// create a map with all children that need to be removed
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
我的数据库:
如何解决此错误?
答案 0 :(得分:2)
您似乎正在尝试将需要节点8的代码(因为它使用=>
表示法)部署到不支持它的环境中。
解决方案是升级环境以支持节点8。另一种方法是修改代码以不再需要节点8,可以通过以下方式完成:
exports.deleteOldItems = functions.database.ref('/mensagens/{idone}/{idtwo}/{pushid}').onWrite(function(change) {
var ref = change.after.ref.parent; // reference to the parent
var now = Date.now();
var cutoff = now - CUT_OFF_TIME;
var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
return oldItemsQuery.once('value').then(function(snapshot) {
// create a map with all children that need to be removed
var updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null;
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
});
这种类型的重写在现代JavaScript中相当普遍,因此我认为您是新手。如果您不熟悉JavaScript,则Firebase Cloud Functions不是学习它的最佳方法。我建议先阅读Firebase documentation for Web developers和/或参加Firebase codelab for Web developer。它们涵盖了许多基本的JavaScript,Web和Firebase交互。您还可以在本地Node.js进程中使用Admin SDK,可以使用本地调试器对其进行调试。在那之后,您也将更有能力为Cloud Functions编写代码。