hamburger

主に日記

Firebase Cloud FunctionsでRealtime Databaseに書き込む

前回

hamburger.hatenablog.jp

公式を見ながら進めている途中

firebase.google.com

関数を書いてみる

index.jsにhello worldのコードがコメントアウトされた状態で記載されている。 ここは無視して最初の関数を記載する。

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

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions

// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

Cloud Functionsの設定と、Realtime Databaseにアクセスするための宣言をする。

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

次に関数の宣言 - httpリクエスト用の関数 - 同期的にリクエストをさばくためasyncを利用 - 最後にリダイレクトさせる

// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.addMessage = functions.https.onRequest(async (req, res) => {
  // Grab the text parameter.
  const original = req.query.text;
  // Push the new message into the Realtime Database using the Firebase Admin SDK.
  const snapshot = await admin.database().ref('/messages').push({original: original});
  // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
  res.redirect(303, snapshot.ref.toString());
});

デプロイする

$ firebase deploy --only functions

実行後、関数とoverviewのURL2つが表示される。

まずは関数を実行してみる。ブラウザ上で https://{個人のurl}.cloudfunctions.net/addMessage?text=hogehoge を開くと、Realtime Databaseのページにリダイレクトされた。

f:id:burgerham:20200429114328p:plain
パラメータに設定したテキストが保存されている

ちなみに別のテキストを再度URLを叩くと、updateではなくinsertとしてmessages配下に登録された。

別の関数を書いてみる

今度はRealtimeDatabaseのcreateをトリガーとして、対象テキストを読み取り、変換して保存する関数。

// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const original = snapshot.val();
      console.log('Uppercasing', context.params.pushId, original);
      const uppercase = original.toUpperCase();
      // You must return a Promise when performing asynchronous tasks inside a Functions such as
      // writing to the Firebase Realtime Database.
      // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
      return snapshot.ref.parent.child('uppercase').set(uppercase);
    });

先ほどと同様にデプロイし、再度addMessageのURLを実行してみる。すると、messages配下にoriginalとは別に、uppercaseも登録された

f:id:burgerham:20200429115606p:plain
`thisisapen`と入力した結果

そのほか

cloud functions for firebaseの実態はGCPのcloud functionsらしく、overviewのページからGCPの管理ページに移動できる。関数の登録や更新もできそうなので、ローカルでやりたくない場合はこっちで編集するのもはありかもしれない