简体   繁体   English

从 Firebase 函数中的 Firestore 获取数据时遇到问题

[英]trouble obtaining data from Firestore in Firebase Functions

I am trying to catch the update of a document and send a notification to all users but the catch value I'm having trouble parsing it.我正在尝试捕获文档的更新并向所有用户发送通知,但捕获值我无法解析它。

in the console.log() this is the catch data:在 console.log() 这是捕获数据:

{ createdAt: Timestamp { _seconds: 1586881980, _nanoseconds: 0 },
  messages: 
   [ { content: 'Un nuevo comienzo para tod@s!\n:)\n😀\n:-P\n😉',
       createdAt: [Object],
       displayName: 'Fer...',
       photoUrl: 'https://lh3.googleusercontent.com/...',
       uid: 'IJchaq...' },
     { content: '🙋',
       createdAt: [Object],
       displayName: 'IMP...',
       photoUrl: 'https://lh3.googleusercont...' } 
       ...

and this is my function:这是我的 function:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();

// const db = admin.firestore();
const fcm = admin.messaging();

export const sendToTopic = functions.firestore
  .document("chats/{chatsId}")
  .onUpdate((change, context) => {

    const newValue = change.after.data();

    // console.log(newValue);

    let latestMessage = newValue.messages[0]; // newValue gives me object is possibly 'undefined'

    const payload: admin.messaging.MessagingPayload = {
      notification: {
        title: "New Message",
        body: latestMessage,
        icon:
          "https://www.dropbox...",
        clickAction: "FLUTTER_NOTIFICATION_CLICK",
      },
    };

    return fcm.sendToTopic("globalChat", payload);
  });

how do I get the latest displayName and the content from the newValue?如何从 newValue 中获取最新的 displayName 和内容?

I solved it by changing to newValue?messages[0];我通过更改为newValue?messages[0];解决了它

EDIT: Have deleted my previous solution because it introduced new errors as per comments by @fenchai.编辑:已删除我以前的解决方案,因为它根据@fenchai 的评论引入了新错误。 The crux of the problem is of course dealing with values in typescript, that are possibly null or undefined.问题的症结当然是处理 typescript 中的值,这些值可能是 null 或未定义。 Typescript will want you to null check them. Typescript 会希望你去 null 检查他们。

I looked further into this and this SF post had more clarification: https://stackoverflow.com/a/58401023/10303131我对此进行了进一步调查,这篇 SF 帖子有更多说明: https://stackoverflow.com/a/58401023/10303131

As @fenchai notes, you can use the?正如@fenchai 所说,您可以使用? operator.操作员。

Please read release notes of Typescript, as of late 2019: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html请阅读 Typescript 的发行说明,截至 2019 年底: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.ZFC35FDC70D5FC2C75D269883A28

Items of interest:感兴趣的项目:

Optional Chaining:可选链:

// Make x = foo.bar(). If foo null or undefined, x will be undefined.
let x = foo?.bar()

Nullish Coalescing:无效合并:

// Makes x equal to foo, or if it is null/ undefined, call bar(). 
let x = foo ?? bar();

From a firebase functions point of view, I would still recommend to anyone that they null check important variables before calling further code, as you will have a chance to clarify important errors, as firebase functions may not always tell you which value is undefined and the root cause of the problem.从 firebase 函数的角度来看,我仍然向任何人建议他们 null 在调用进一步代码之前检查重要变量,因为您将有机会澄清重要错误,因为 ZBF12E1515C25C7D8C0352F1413AB9A1 告诉您哪些函数可能未定义问题的根本原因。

Example:例子:

const message = myDocument?.data()?.message;
if (message === null || message === undefined){
    console.error("Message is undefined or null");
    // Proceed, or return if message vital to function.  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM