Firebase云函数admin.messaging.send()不是函数

时间:2020-07-15 13:56:35

标签: javascript firebase google-cloud-functions firebase-cloud-messaging firebase-admin

我在index.js中创建了一个函数,该函数在用户每次有新的活动供稿项时都会向用户发送通知,例如有人喜欢帖子或发表评论或发送消息时。当我运行它时,我在firebase上的函数日志中遇到了此错误:

TypeError: admin.messaging.send is not a function
    at sendNotification (/workspace/index.js:220:8)
    at exports.onCreateActivityFeedItem.functions.firestore.document.onCreate (/workspace/index.js:176:5)
    at process._tickCallback (internal/process/next_tick.js:68:7)

我已经尝试过npm install firebase-admin@latest,但没有解决问题。这是我在index.js中创建的功能

exports.onCreateActivityFeedItem = functions.firestore
.document('/feed/{userId}/feedItems/{activityFeedItem}')
.onCreate(async (snapshot, context) => {
  console.log('Activity feed item created', snapshot.data());

  // 1) Get user connected to the feed
  const userId = context.params.userId;

  const userRef = admin.firestore().doc(`users/${userId}`);
  const doc = await userRef.get();

  // 2) Once we have user, check if they have a notification token; 
  //send notification if they have token
  const androidNotificationToken = doc.data().androidNotificationToken;
  const createdActivityFeedItem = snapshot.data();
  if (androidNotificationToken) {
    sendNotification(androidNotificationToken, createdActivityFeedItem);
  } else {
    console.log('No token for user, cannot send notification');
  }

  function sendNotification(androidNotificationToken, activityFeedItem){
    let body;

    // 3) switch body based on activity feed item type
    switch (activityFeedItem.type) {
      case 'comment':
        body = `${activityFeedItem.username} replied: 
        ${activityFeedItem.commentData}`;
        break;
        case 'like':
          body = `${activityFeedItem.username} liked your post`;
        break;
        case 'follow':
          body = `${activityFeedItem.username} started following you`;
        break;
        case 'request':
          body = `${activityFeedItem.username} needs a tutorial in ${activityFeedItem.postId}`;
        break;
        case 'accepted':
          body = `${activityFeedItem.username} accepted your 
          ${activityFeedItem.postId} request`;
        break;
        case 'message':
          body = `${activityFeedItem.username} sent you a message`;
        break;
      default:
        break;
    }

    // 4) Create message for push notification
    const message = {
      notification: {body},
      token: androidNotificationToken,
      data: {recipient: userId},
    }

    // 5) Send message with admin.messaging()
    admin
      .messaging
      .send(message)
      .then(response => {
        // response is a message ID string
        console.log('Succesfully sent message', response)
      })
      .catch(error => {
        console.log('Error sending message', error)
      });
  }
});

1 个答案:

答案 0 :(得分:1)

您需要在括号中使用admin.messaging()。就像您已经使用admin.firestore()一样,它是一个函数调用,而不是属性。