Firebase函数错误-对象可能是'undefined'

时间:2020-05-12 19:27:34

标签: typescript firebase google-cloud-firestore google-cloud-functions

我正在尝试向Firebase部署一个简单的功能。

在集合write中创建新的todos时,我希望使用令牌将通知发送给订户:

evGBnI_klVQYSBIPMqJbx8:APA91bEV5xOEbPwF4vBJ7mHrOskCTpTRJx0cQrZ_uxa-QH8HLomXdSYixwRIvcA2AuBRh4B_2DDaY8hvj-TsFJG_Hb6LJt9sgbPrWkI-eo0Xtx2ZKttbIuja4NqajofmjgnubraIOb4_

为了实现这一目标,我遵循了一个教程,但是在部署时却出现了错误

下面是我的function的代码:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

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

exports.newSubscriberNotification = functions.firestore
.document('todos')
.onCreate(async event=>{
    const data = event.data();
    const workdesc = data.workdesc;
    const subscriber = "evGBnI_klVQYSBIPMqJbx8:APA91bEV5xOEbPwF4vBJ7mHrOskCTpTRJx0cQrZ_uxa-QH8HLomXdSYixwRIvcA2AuBRh4B_2DDaY8hvj-TsFJG_Hb6LJt9sgbPrWkI-eo0Xtx2ZKttbIuja4NqajofmjgnubraIOb4_";

// notification content
const payload = {
    notification: {
        title: 'new write in collection todos',
        body: workdesc,
       //body: 'body',
        icon: 'https://img.icons8.com/material/4ac144/256/user-male.png'
    }
}

// send notification
return admin.messaging().sendToDevice(subscriber, payload)

});

错误:

src/index.ts:11:11 - error TS6133: 'workdesc' is declared but its value is never read.

11     const workdesc = data.workdesc;
             ~~~~~~~~

src/index.ts:11:22 - error TS2532: Object is possibly 'undefined'.

11     const workdesc = data.workdesc;

Found 2 errors.

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! functions@ build: `tsc`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the functions@ build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

编辑1

按照说明进行2次更改后,当我部署该功能时,它仍会显示HTTP Error: 400,并附带屏幕截图

enter image description here

1 个答案:

答案 0 :(得分:1)

TypeScript错误消息告诉您有两个问题。

首先,您尝试访问的对象的属性可能是未定义的,这将导致崩溃。 data可能是未定义的,因为这是函数签名的一部分。实际上,对于onCreate函数来说,永远都不会定义它,因此您可以使用!运算符来覆盖它,以告诉TypeScript您确保它永远不会被定义:

    const data = event.data()!;

另一个错误是告诉您您只是声明了一个从未使用过的变量。您声明了workdesc,但从未使用过。只需删除它-不需要代码。如果需要使用它,那就这样做。

相关问题