admin.messaging(...)。send不是一个函数

时间:2018-03-05 22:53:18

标签: firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions firebase-admin

我正在使用firebase-admin通过Cloud Functions发送推送通知,但我一直收到此错误:

TypeError: admin.messaging(...).send is not a function
    at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:43:27)
    at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
    at next (native)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
    at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
    at /var/tmp/worker/worker.js:700:26
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

知道它为什么不起作用?我使用的是firebase-admin版本5.9.1,所以它是最新版本。它应该包含 .send 功能,但它仍然不起作用。我已经卸载了该插件并重新安装了它,但仍然没有用。

这是我正在使用的代码:

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

admin.initializeApp({
  credential: admin.credential.cert({
    projectId: "xxx",
    clientEmail: 'xxx@xxx.iam.gserviceaccount.com',
    privateKey: '-----BEGIN PRIVATE KEY-----<KEY>-----END PRIVATE KEY-----\n'
  }),
  databaseURL: "https://xxx.firebaseio.com"
});

exports.sendNotification = functions.database.ref("xxx").onWrite((event) => {
    console.log("notify");

    const registrationToken = "xxx";

    // See documentation on defining a message payload.
    var message = {
        notification: {
            title: "You have a new service request",
            body: "this is the main body"
        },
        data: {
            score: '850',
            time: '2:45'
        },
        token: registrationToken
    };

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

我做错了什么?

1 个答案:

答案 0 :(得分:2)

它应该是sendToDevice而不是send,可能是这样的:

var message = {
    notification: {
        title: "You have a new service request",
        body: "this is the main body"
    },
    data: {
        score: '850',
        time: '2:45'
    }
};

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