云功能在本地运行,但在部署之后不能运行

时间:2018-05-31 04:52:06

标签: javascript firebase firebase-realtime-database google-cloud-functions

我正在编写我的第一个Cloud Function,用微笑取代“happy”这个词。

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

admin.initializeApp();

exports.emojify = functions.database.ref("/messages/{pushId}/text").onWrite((change, context) => {
    const original = change.before.val();
    const emojified = emojifyText(original);

    return admin.database().ref().set(emojified);
});

function emojifyText(text) {
    let t = text;
    t = t.replace(/\b(H|h)appy\b/ig, "");

    console.log("Result:", t);

    return t;
};

我发现我可以在部署之前通过运行firebase functions:shell进行测试并执行以下操作:

firebase > emojify({ before: "Happy!" })
'Successfully invoked function.'
firebase > info: User function triggered, starting execution
info: Result: !
info: Execution took 2949 ms, user function completed successfully

有效。但是,在使用我的Android应用程序进行测试时,我的功能日志将显示:

TypeError: Cannot read property 'replace' of null
    at emojifyText (/user_code/index.js:15:13)
    at exports.emojify.functions.database.ref.onWrite (/user_code/index.js:8:23)
    at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
    at next (native)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
    at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
    at /var/tmp/worker/worker.js:716:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

我不明白。

经过一些新尝试后,我的代码如下:

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

admin.initializeApp();

exports.emojify = functions.database.ref("/messages/{pushId}/text").onWrite((change, context) => {
    // if (!change.before.val()) { return null; } 
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    // I tried with this and without it, but neither helped.

    const original = change.after.val();
    const emojified = original.replace(/\b(H|h)appy\b/ig, "");

    return admin.database().ref("/messages/{pushId}/text").update(emojified);
});

我最接近的是实际删除基础中的所有内容,包括路径messages,并将其替换为书面文本,文本替换为表情符号。类似的东西:

enter image description here

但它使用的是set()而不是update(),它没有显示任何修改内容的迹象。

1 个答案:

答案 0 :(得分:1)

const original = change.before.val();之前的数据。因此,如果在写入"/messages/{pushId}/text"节点之前没有数据,则变量original将为空。

你应该改为:

const original = change.after.val();这是写入后 的数据,即你想要“emojify”的新数据。

根据您的评论更新

您应该使用update()方法(文档here),如下所示:

return admin.database().ref("/messages/" + context.params.pushId + "/").update({ text: emojified });