なぜかわかりませんが、cloud functionsから外部apiから取得した情報をrealtime databaseへ保存する過程で、保存が成功したり、しなかったりしてしまいます。
どういうことかといいますと、
// realtime databese上でユーザが作成されたら以下が走る exports.deviceRegister = functions.auth.user().onCreate(event => { // ここでユーザuidを取得している。 const user = event.uid; console.log(user) // ここは毎回走っている console.log("1"); // 新しく作成されたユーザの/Users/${user}/deviceTokenパス以下の情報を参照、 db.ref(`/Users/${user}/deviceToken`).on("value", function(snapshot) { console.log(snapshot.val()); // 参照した情報がnullなら、 if(snapshot.val() === null){ console.log("デバイストークンが取得できていないよ") }else{ console.log("デバイストークンが取得できたよ") // Onesignalへデバイストークンを登録するためのメソッド == ここから // nullじゃなければ以下の処理が走る var request = require("request"); var options = { method: 'POST', url: 'https://hogehoge.com/api/v1/players', headers: { 'cache-control': 'no-cache', 'Content-Type': 'application/json' }, body: { app_id: '242******************3', identifier: snapshot.val(), language: 'en', timezone: -28800, game_version: '1.0', device_os: '7.0.4', device_type: 0, device_model: 'iPhone', tags: { a: '1', foo: 'bar' } }, json: true }; request(options, function (error, response, body) { if (error) throw new Error(error); console.log(body["id"]); console.log(response); // ここが走ったり走らなかったり、 console.log("2"); // 以下の処理がrealtime databaseへ保存する処理 db.ref(`/Users/${user}/`).update({ "playerid": body["id"] }); }); return 0; }}, function(errorObject) { console.log("The read failed: " + errorObject.code); } ); // ここは毎回走っていることを確認できている console.log("3"); })
という感じで、以下の処理が走らずに終了してしまいます。
db.ref(`/Users/${user}/`).update({ "playerid": body["id"] });
しかし、処理が正常に機能することもあり訳が分からず困っております。
私の理解としては、以下処理が終了する前に
request(options, function (error, response, body) { if (error) throw new Error(error); console.log(body["id"]); console.log(response); // ここが走ったり走らなかったり、 console.log("2"); // 以下の処理がrealtime databaseへ保存する処理 db.ref(`/Users/${user}/`).update({ "playerid": body["id"] });
以下の処理が終了しているため上記の処理が動作しないと考えております。
exports.deviceRegister = functions.auth.user().onCreate(event =>
なぜ起こるものなのか、ご存知の方いましたらご教授のほどよろしくお願いします。
回答1件
あなたの回答
tips
プレビュー