2017-07-08 6 views
0

データベーストリガーが呼び出されたときにユーザーに通知を送信するFirebase Cloud機能を使用しています。登録トークンはfirebaseデータベースに保存されます。問題は、登録トークンが救われたこと、これらのデバイスに通知が表示されないことです。 これはindex.jsデータベースのトリガーに通知が表示されない

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 



exports.sendNotification = functions.database.ref('/Blog').onWrite(event => { 
const title = event.data.child('title').val(); 

const token_no = event.data.child('token_no').val(); 


    const getDeviceTokensPromise = admin.database().ref(`/Token/${token_no}`).once('value'); 
    const getBody=admin.database().ref(`/Blog`).once('value'); 

    return Promise.all([getDeviceTokensPromise,getBody]).then(results => { 
    const tokensSnapshot = results[0]; 
    const notify=results[1]; 




    if (!tokensSnapshot.hasChildren()) { 
     return console.log('There are no notification tokens to send to.'); 
    } 
    console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.'); 


    // Notification details. 
    const payload = { 
     notification: { 
     title: 'You have a new Alert!', 
     body: `${notify.child('title').val()}`, 

     } 
    }; 

    // Listing all tokens. 
    const tokens = Object.keys(tokensSnapshot.val()); 

    // Send notifications to all tokens. 
    return admin.messaging().sendToDevice(tokens, payload).then(response => { 
     // For each message check if there was an error. 
     const tokensToRemove = []; 
     response.results.forEach((result, index) => { 
     const error = result.error; 
     if (error) { 
      console.error('Failure sending notification to', tokens[index], error); 
      // Cleanup the tokens who are not registered anymore. 
      if (error.code === 'messaging/invalid-registration-token' || 
       error.code === 'messaging/registration-token-not-registered') { 
      tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove()); 
      } 
     } 
     }); 
     return Promise.all(tokensToRemove); 
    }); 
    }); 
}); 

データベースのスナップショットです:アップデート2

"Token" : { 
"token_no" : { 
    "ctxjePemYZE:APA91bFJXXyTkyvXOlSY...4VbWu7Vbf7itwbwZu9umSvg_tdB1lKD1d8g" : "true", 
    "dgVszInjIW0:APA91bFZE3Av5unZTgp...RUeYb-CUhWjO1otqguhE9NTQZ8XgK6nRIW5" : "true" 
} 

}

答えて

1

あなたのコードは、トークンを取得するためにObject.keys(tokensSnapshot.val())を使用しています。つまり、トークンはtoken_noのキーでなければならず、値ではありません。このように:

"Token" : { 
    "-KoWsMn9rCIitQeNvixr" : { 
    "dK1FjGbNr6k:APA91b...S8JK2d69JpO" : "123" // token is the key, value is not significant; could be "123", true, or 0. 
    }, 
    ... 
} 

更新:

あなたがparamsdata性質のより良い理解を得るために、データベース・トリガーのdocumentation for the Event parameterを確認してください。 paramsは、トリガー参照のワイルドカードにアクセスします。dataがスナップショットです。あなたのコードでは、スナップショットから値を取得する必要があります。

これらの変更を追加します。

const title = event.data.child('title').val(); 
const desp = event.data.child('desp').val(); 
const token_no = event.data.child('token_no').val() 

const payload = { 
    notification: { 
    title: 'You have a new Alert!', 
    body: `${Post.child('title').val()}`, // <= CHANGED 
    //icon: follower.photoURL 
    } 
}; 

は、あなたが投稿したコードを実行すると、これらの変更で、私は通知を送信し、受信することができています。

2つの問題があります。最初の文は次のとおりです。

const getDeviceTokensPromise = admin.database().ref(`/Token/{token_no}`).once('value'); 

token_noが定義されていません。そして、あなたはそれを定義しませんし、その値を代用したい場合、あなたは$を追加する必要があります。

`/Token/${token_no}` 

第二の問題は、失敗する機能の実行を引き起こす、Postが定義されていないということです。機能ログを確認してください:

const payload = { 
    notification: { 
    title: 'You have a new Alert!', 
    body: `${Post.title}`, 
    //icon: follower.photoURL 
    } 
}; 
+0

JavaScriptの知識がほとんどないので、コードが正しいかどうか確認してください。また、編集したコードを実行した後、実行されますが、クラウド機能のログには「送信先の通知トークンはありません」と表示されます。しかし、トークンはデータベースに保存されています。コードがどこに間違っているのか分かりません。 –

+0

それはまだ同じです!まだトークンがないことをログに示しています。トークンを生成するためにFirebaseInstanceIdを作成する必要があります。またはindex.jsが自動的にそれを行いますか? –

+0

アプリの各インスタンスは、(例えば) 'FirebaseInstanceId.getInstance()。getToken()'を使ってトークンを保存し、それをデータベースに格納する必要があります。 –

関連する問題