云功能本地可以使用,但是部署后就不行了

问题描述 投票:0回答:1

我正在编写我的第一个云函数,它用微笑取代了“快乐”这个词。

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
,并将其替换为书面文本,并将文本替换为表情符号。比如:

但它使用的是

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

javascript firebase google-cloud-platform firebase-realtime-database google-cloud-functions
1个回答
0
投票

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

您应该更改为:

const original = change.after.val();

这是写入后
之后的数据,即您想要“表情化”的新数据。


根据下面的评论进行更新

您应该使用

update()

方法(文档

这里
),如下所示: return admin.database().ref("/messages/" + context.params.pushId + "/").update({ text: emojified });

© www.soinside.com 2019 - 2024. All rights reserved.