Reputation: 2525
I am trying to deploy a simple function to Firebase.
When a new write
is made in collection todos
, I want a notification to be sent to a subscriber with token:
evGBnI_klVQYSBIPMqJbx8:APA91bEV5xOEbPwF4vBJ7mHrOskCTpTRJx0cQrZ_uxa-QH8HLomXdSYixwRIvcA2AuBRh4B_2DDaY8hvj-TsFJG_Hb6LJt9sgbPrWkI-eo0Xtx2ZKttbIuja4NqajofmjgnubraIOb4_
In order to achieve this, I followed a tutorial but while deploying, it is giving error
Below is the code of my 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)
});
error :
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.
After the 2 changes as guided, when I am deploying the function, it is still giving HTTP Error: 400
, screenshot attached
Upvotes: 0
Views: 499
Reputation: 317968
The TypeScript error messages are telling you that you have two problems.
First, you're trying to access a property of an object that could be undefined, which would result in a crash. data
could be undefined, because that's part of the signature of the function. In practice, for an onCreate function, it will never be defined, so you can override it like this with the !
operator to tell TypeScript you are sure it will never be undefined:
const data = event.data()!;
The other error is telling you that you simply declared a variable that was never used. You declared workdesc
, but never used it. Just remove it - it's not necessary to your code. If you need to use it, then do so.
Upvotes: 2