为什么我不能将Flutter JavaScript部署到firebase云函数

v8wbuo2f  于 2023-06-30  发布在  Flutter
关注(0)|答案(1)|浏览(109)

我正在一个Flutter项目中实现push-notifications。我希望Firebase函数在数据库中的某个collection发生更改时触发通知。
使用JavaScript编写函数。Node version: 16

复制:

步骤1:firebase init functions
第二步:? Please select an option: Use an existing project
步骤3:? Select a default Firebase project for this directory: my-project-1 (my-project-1)
第四步:? What language would you like to use to write Cloud Functions? JavaScript
第五步:? Do you want to use ESLint to catch probable bugs and enforce style? Yes
第6步:index.js的JavaScript代码

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

// fcm notification
exports.sendNotification = functions.firestore
  .document("rooms/{roomId}/")
  .onWrite(async(change, context) => {

    const payload = {
      "notification":{
        "title": "Firebase messaging",
        "body": "A message",
      },
    };
    const options = {};
    return admin.messaging().sendToDevice('TOKEN-ID', payload, options);
  });

步骤7:npm run deploy
当部署到firebase时,这是返回的错误:

9:34  error  Parsing error: Unexpected token =>

✖ 1 problem (1 error, 0 warnings)

Error: functions predeploy error: Command terminated with non-zero exit code 1
noname@inoname functions % npm run deploy

这就是包。json:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "16"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^10.0.2",
    "firebase-functions": "^3.18.0"
  },
  "devDependencies": {
    "eslint": "^8.9.0",
    "eslint-config-google": "^0.14.0",
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}
n3schb8v

n3schb8v1#

ChatGPT问,它为我提供了这段代码,不知何故工作。我看不出有什么不同,但现在它起作用了:

  • 编辑:发现是async属性导致了问题。通过删除asyncawait,编译并部署了
const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

exports.chatMessageNotification = functions.firestore
    .document("rooms/{roomId}")
    .onUpdate((change, context) => {
      const newData = change.after.data();
      const previousData = change.before.data();

      if (newData.updatedAt !== previousData.updatedAt) {
         // Perform your notification sending logic here
         // Use newData and previousData to access the updated and previous document data
         // Send the notification to the desired device token
      }
    });

相关问题