Firebase Cloud Functions未写入数据库

时间:2019-04-02 20:28:07

标签: javascript node.js firebase firebase-realtime-database google-cloud-functions

我正在尝试编写一个Firebase Cloud函数,该函数将在每次调用时在数据库中写入当前时间:

const admin = require('firebase-admin');
const functions = require('firebase-functions');

admin.initializeApp(functions.config().firebase);

exports.pushDateOfCall = functions.https.onRequest((req, res) => {

    const currentTime = new Date();

    return admin.database().ref('/dates').push({currentTime: currentTime}).then((snapshot) => {
        return res.send("Complete");
      }).catch((error) => res.send("Something went wrong"));
  });

在部署函数并从函数的URL对其进行调用之后,数据库内部不会写入任何内容。

firebase功能日志的输出:

Function execution took 1358 ms, finished with status code: 304

P.S。我希望从隐身模式开始运行该链接,因为我希望调用该链接的人(无论是经过授权的还是未经授权的)都可以使用它。

2 个答案:

答案 0 :(得分:2)

const currentTime = new Date();

currentTime是一个对象。如果要存储日期的字符串,请使用String(currentTime)作为

return admin.database().ref('/dates').push({currentTime: String(currentTime)})

答案 1 :(得分:1)

@hkchakladar是正确的,将其更改为{currentTime: String(currentTime)}将解决此问题。

但是,请注意,您无需返回res.send()或返回异步push()方法返回的承诺。 Firebase有关HTTP Cloud Function的官方视频中对此进行了显示,请参见https://www.youtube.com/watch?v=7IkUgCLr5oA

所以您的代码可能如下:

exports.pushDateOfCall = functions.https.onRequest((req, res) => {
  const currentTime = new Date();

  admin
    .database()
    .ref('dates')
    .push({ currentTime: String(currentTime) })
    .then(ref => {
      res.send('Complete');
    })
    .catch(error => res.status(500).send('Something went wrong'));
});