创建Firebase函数时,Google示例无法正常运行

时间:2018-08-15 17:05:50

标签: javascript android function firebase google-cloud-functions

我正在尝试创建一个向我写入数据库时​​发送通知的云函数,我对JavaScript几乎一无所知,因此我尝试使用Google样本here之一,但它们使用的是语法我的node.js不喜欢,所以我更新了工具,并根据this向我的package.json添加了node 8引擎,但是在尝试部署此功能时仍然出现错误,错误是

Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:9
    .onWrite(async (change, context) => {
                   ^

有人可以帮我解决这个问题吗,这是我的整个index.js脚本

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup 
triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

exports.sendNotification = 
functions.database
.ref('/user/{userId}/contacts/{contactId}/messages/{messageId}')
.onWrite(async (change, context) => {
  const senderId = context.params.userId;
  const recipientId = context.params.contactId;
  // If update or delete we exit the function
  if (!change.after.val()) {
    return console.log('User updated or deleted');
  }
  //get the message
  const message = change.data.current.val();

  console.log('We have a new message for ', recipientId, ' from user: ', senderId);

  // Get the recipient profile.
  const getRecipientProfile = await admin.auth().getUser(recipientId);
  //get token
  const token = getRecipientProfile.registeredToken;

  // Notification details.
  const payload = {
    notification: {
      title: 'New message',
      body: message.message,
      icon: getRecipientProfile.user_small_image
    }
  };

  // Send notification

  admin.messaging().sendToDevice(token, payload)
        .then(function (response) {
            console.log("Successfully sent message:", response);
        })
        .catch(function (error) {
            console.log("Error sending message:", error);
        });

});

和我的package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
  "serve": "firebase serve --only functions",
  "shell": "firebase functions:shell",
  "start": "npm run shell",
  "deploy": "firebase deploy --only functions",
  "logs": "firebase functions:log"
},
"engines": {
  "node": "8"
},
"dependencies": {
  "firebase-admin": "~5.12.1",
  "firebase-functions": "^1.0.3"
},
"private": true
}

1 个答案:

答案 0 :(得分:0)

您可以尝试更改

.onWrite(async (change, context) => 

.onWrite((change, context) => 

基本上删除async