【问题标题】:Value of firebase functions onwrite sometimes is nullfirebase 函数 onwrite 的值有时为空
【发布时间】:2019-08-10 13:32:17
【问题描述】:

我正在尝试实现一个 Android 订购系统,并且我正在使用实时数据库。为了发送通知,我在 JavaScript 中使用 Firebase 函数。

每个用户连同他们的 ID、发送通知的令牌以及其他数据一起存储在数据库中。 我要做的是检测用户何时收到订单并向他们发送通知

问题出现在这里。 在某些情况下会发送通知,而在其他情况下则不会。查看我的“sendNotif”函数的日志,我发现错误是这样的:

TypeError: Cannot read property 'idcomprador' of null
    at exports.sendNotif.functions.database.ref.onWrite (/user_code/index.js:133:32)
    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:827:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

我的代码:

exports.sendNotif = functions.database.ref('/Usuarios/{vendedorId}/Solicitudes/Venta/{pushId}').onWrite((change, context) => {

  // Grab the current value of what was written to the Realtime Database.
  const solicitud = change.after.val();
  const compradorId = solicitud.idcomprador
  const pedidoId = solicitud.idpedido
  const vendedorId = solicitud.idvendedor
  var solicitudTokens = [vendedorId];

  // Notification details.
  const payload = {
    notification: {
      title: `Order`,
      body: `order`,
      icon: 'photoURL',
      tag: 'solicitudventa',
      sound: 'default',
      clickAction: 'ACTIVITY_ORDER',
      badge: '2'
    },
    data: {
      extra: 'extra_data',
    },
  };

  const options = {
    collapseKey: 'demo',
    contentAvailable: true,
    priority: 'high',
    timeToLive: 60 * 60 * 24,
  };


var ref = admin.database().ref(`Usuarios/${vendedorId}/token/result/token`);
return ref.once("value", function(snapshot){


        admin.messaging().sendToDevice(snapshot.val(), payload)

        },
    function (errorObject) {
        console.log("The read failed: " + errorObject.code);
    });
    });

第 133 行是这样的:const compradorId = solicitud.idcomprador。 我不明白为什么它有时有效,有时无效。

【问题讨论】:

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


    【解决方案1】:

    onWrite 将触发与触发器位置匹配的任何更改。这意味着它将触发任何创建、更新或删除。

    当触发事件是创建新数据时,change.before 将未定义(之前没有数据),change.after 将包含快照。

    当触发事件为删除数据时,change.before 将包含快照,change.after 将未定义。

    您的代码盲目地假设change.after 包含快照。删除数据完全有可能触发了您的功能,并且它失败了,因为这不是它的设计目的。

    使用 onWrite 时,您有义务检查这种情况并妥善处理。如果您不关心删除事件,请考虑使用 onCreate 来捕获新数据。

    【讨论】:

      猜你喜欢
      • 2017-08-02
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 2018-05-04
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      相关资源
      最近更新 更多