云功能:详细的堆栈跟踪:错误:找不到模块“ fcm-push”

时间:2018-09-19 09:23:28

标签: node.js firebase push-notification google-cloud-firestore npm-install

我正在尝试创建一个在获取设备令牌后将推送通知发送到设备的函数。该功能已正确部署,但该功能在日志中出现错误。正如我在下面提到的,错误是

cannot find module fcm push 

我尝试过:-

$ install npm fcm-push
$ install npm fcm-push --save

这对错误没有任何改变。

函数通知收到此错误:-

{"@type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function load error: Code in file index.js can't be loaded.\nDid you list all required modules in the package.json dependencies?\nDetailed stack trace: Error: Cannot find module 'fcm-push'\n    at Function.Module._resolveFilename (module.js:476:15)\n    at Function.Module._load (module.js:424:25)\n    at Module.require (module.js:504:17)\n    at require (internal/module.js:20:19)\n    at Object.<anonymous> (/user_code/index.js:5:13)\n    at Module._compile (module.js:577:32)\n    at Object.Module._extensions..js (module.js:586:10)\n    at Module.load (module.js:494:32)\n    at tryModuleLoad (module.js:453:12)\n    at Function.Module._load (module.js:445:3)"},"authenticationInfo":{"principalEmail":"muddasar.pixster@gmail.com"},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction","resourceName":"projects/testingproject-80016/locations/us-central1/functions/Notificaation"}

我也明白了

 Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'fcm-push'
at Function.Module._resolveFilename (module.js:476:15)
at Function.Module._load (module.js:424:25)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/user_code/index.js:5:13)
at Module._compile (module.js:577:32)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)

我的package.json是

{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.0.3"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.6.0"
},
"private": true
 }

我的代码是

 'use strict';

 const functions = require('firebase-functions');
 const admin = require('firebase-admin');
 exports.Notificaation = functions.firestore.document("Token/{token_id}").onWrite((change, context) => {


console.log('Toekn id', context.params.token_id);

const req = context.params.token_id;

        return admin.firestore().collection('UseData').doc(id).get()
            .then(snapshot => {
                const uid=snapshot.data().user_id;

                console.log("User id: ", uid);



                  return admin.firestore().collection('UserData').doc(uid).collection('Token').doc(req).get()
                  .then(snap=>
                    {


                            if(uid === null)
                            {
                              console.log("You are not logged in");
                            }
                            else
                            {
                               return admin.firestore().collection('UserData').doc(uid).collection('Join_members').get()
                               .then(snap=>
                                 {

                                      snap.forEach(doc =>{

                                         return admin.firestore().collection("Token").doc(doc.data().user).get()
                                            .then(snapshot2 =>
                                              {
                                               const tid2=snapshot2.data().token_id;

                                               console.log(" Token_id: ",tid2);


                                               const payload2= {
                                                   notification:{
                                                       title:"Notification",
                                                       body:"New Message.",


                                                     },

                                                   data:
                                                    {
                                                    user_id:id,

                                                     message:'1',

                                                   }

                                               };
                                                console.log(payload2);

                                               const options = {
                                                     priority: "high",
                                                     timeToLive: 60 * 60 *24,
                                                     content_available: true,
                                                    };




                                                 return admin.messaging().sendToDevice(tid2, payload2,options).then(result => {

                                                   var db = admin.firestore();

                                                   var data = {

                                                     type:'New Message Arrived',
                                                     status:1,
                                                     timestamp:admin.firestore.FieldValue.serverTimestamp()

                                                   };

                                                   var data1 = {
                                                      notifiction_message:0
                                                   };


                                                   var setDoc = db.collection('UserData').doc(doc.data().user).collection('notification').doc().set(data);

                                                   var setDoc1 = db.collection('UserData').doc(doc.data().user).update(data1);

                                                  return console.log('Notify when New Message ');

                                                 });
                                       });
                                       });
                                       console.log("Sucess");
                                       return true;

                                    });
                            }
                        return true;
                    });
          });
  });

2 个答案:

答案 0 :(得分:0)

您无需使用Cloud Function中的fcm-push模块。

云功能将仅用于发送通知。

为了获取客户端设备的FCM令牌,您应该在客户端实施特定的代码。

请参阅下面的官方Firebase示例,它们在其中实现了这种机制:https://github.com/firebase/functions-samples/tree/master/fcm-notifications(节点6的版本)。

看看下面的JS file,其中在第184到211行实现了发送令牌的逻辑。下面粘贴了代码以供将来参考。

在此示例中,当用户获得新关注者时触发通知发送(请参见index.js Cloud Function文件):

exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}')
.onWrite((change, context) => {})

由于您已经(在注释中)表示要向“登录我的应用程序的用户”发送通知,因此,您应该创建自己的触发机制,因为没有开箱即用的触发机制用户登录,请参见Can Cloud Functions for Firebase execute on user login?


令牌发送示例代码的摘录:

// Saves the token to the database if available. If not request permissions.
Demo.prototype.saveToken = function() {
  firebase.messaging().getToken().then(function(currentToken) {
    if (currentToken) {
      firebase.database().ref('users/' + this.currentUid + '/notificationTokens/' + currentToken).set(true);
    } else {
      this.requestPermission();
    }
  }.bind(this)).catch(function(err) {
    console.error('Unable to get messaging token.', err);
    if (err.code === 'messaging/permission-default') {
      this.fcmErrorContainer.innerText = 'You have not enabled notifications on this browser. To enable notifications reload the page and allow notifications using the permission dialog.';
    } else if (err.code === 'messaging/notifications-blocked') {
      this.fcmErrorContainer.innerHTML = 'You have blocked notifications on this browser. To enable notifications follow these instructions: <a href="https://support.google.com/chrome/answer/114662?visit_id=1-636150657126357237-2267048771&rd=1&co=GENIE.Platform%3DAndroid&oco=1">Android Chrome Instructions</a><a href="https://support.google.com/chrome/answer/6148059">Desktop Chrome Instructions</a>';
    }
  }.bind(this));
};

// Requests permission to send notifications on this browser.
Demo.prototype.requestPermission = function() {
  console.log('Requesting permission...');
  firebase.messaging().requestPermission().then(function() {
    console.log('Notification permission granted.');
    this.saveToken();
  }.bind(this)).catch(function(err) {
    console.error('Unable to get permission to notify.', err);
  });
};

答案 1 :(得分:0)

您可能必须将其添加到依赖项中(相当于本地npm install fcm-push):

"dependencies": {
    ...
    "fcm-push": "1.1.3"
},

,然后在代码中要求它:

var FCM = require('fcm-push');