« Firebase Functions 1 | メイン | Screen Code Analyzer から firebase へデータ送信 »

javascript

Firebase Functions + Firestore

 Google の Firebase Cloud Functions スタートガイド(第2世代)前回に引き続き 手元PCのブラウザだけで 動作を確認する手順備忘録。 サンプルは、

●HTTPSリクエストしたメッセージをネット上のデータベースに登録
●データベース登録時に大文字変換した列を追加
するもの。
...▼
■Firebase Console
https://console.firebase.google.com/
 前回作成したプロジェクト[myProject]

 トップメニュー / 構築 / Firestore Database

 データベースの作成

資料:Cloud Firestore を使ってみる(「Cloud Firestore データベースを作成する」まで)

資料:データベースを比較

資料:実現できること

 テストモードで開始

 ロケーションは応答速度や課金単価と相談。



 必ずしも事前にスキーマ定義不要。

■Google Cloud Shell
https://console.cloud.google.com/
Cloud Shell Editor
https://console.cloud.google.com/cloudshelleditor
 プロジェクト別にフォルダを作成し その中での作業がお勧め。
$ mkdir ~/myProject1
$ cd ~/myProject1

 Firestore 初期化
$ firebase init firestore


 Functions 初期化
$ firebase init functions
ここでは前回の functions/index.js を上書き。



 スタートガイド(第2世代) で用意されるサンプルコードで置き換え。
$ vi ~/functions/index.js
// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const {logger} = require("firebase-functions");
const {onRequest} = require("firebase-functions/v2/https");
const {onDocumentCreated} = require("firebase-functions/v2/firestore");

// The Firebase Admin SDK to access Firestore.
const {initializeApp} = require("firebase-admin/app");
const {getFirestore} = require("firebase-admin/firestore");

initializeApp();

// Take the text parameter passed to this HTTP endpoint and insert it into
// Firestore under the path /messages/:documentId/original
exports.addmessage = onRequest(async (req, res) => {
  // Grab the text parameter.
  const original = req.query.text;
  // Push the new message into Firestore using the Firebase Admin SDK.
  const writeResult = await getFirestore()
      .collection("messages")
      .add({original: original});
  // Send back a message that we've successfully written the message
  res.json({result: `Message with ID: ${writeResult.id} added.`});
});

// Listens for new messages added to /messages/:documentId/original
// and saves an uppercased version of the message
// to /messages/:documentId/uppercase
exports.makeuppercase = onDocumentCreated("/messages/{documentId}", (event) => {
  // Grab the current value of what was written to Firestore.
  const original = event.data.data().original;

  // Access the parameter `{documentId}` with `event.params`
  logger.log("Uppercasing", event.params.documentId, original);

  const uppercase = original.toUpperCase();

  // You must return a Promise when performing
  // asynchronous tasks inside a function
  // such as writing to Firestore.
  // Setting an 'uppercase' field in Firestore document returns a Promise.
  return event.data.ref.set({uppercase}, {merge: true});
});

 デプロイ
$ firebase deploy --only functions
2回ほどリトライ。
Function URL が示される。

 関数一覧
$ firebase functions:list


■Firebase Console → Functions
https://console.firebase.google.com/
 関数一覧

︙/ ログから動作確認可能。

デプロイで示されたFunction URLにパラメータを追加しブラウザでリクエスト。
正常時JSON形式 応答例
{"result":"Message with ID: AYE3lVWf5OvlIhTJa4ox added."}

アドレス:#1#/?text=#2#
#1#:Function URL
#2#:Firestore に登録するメッセージ
●関数の実行例
https://addmessage-yukh3omtca-uc.a.run.app/?text=remix

■Firebase Console → Firestore
https://console.firebase.google.com/
●表(table)に相当するコレクション[messages]

●行(record)に相当するドキュメント[キー]

●列に相当するフィールド[original]とデータ[remix]

●トリガー[makeuppercase]で追加されたフィールド[uppercase]と加工されたデータ[REMIX]

資料:Cloud Firestore トリガー(第2世代)
■確認が終わったらFunctions URL をイタズラされ課金されないよう関数 削除!

トラックバック

このエントリーのトラックバックURL:
https://www.remix.asia/cgi/mt/mt-tb.cgi/7754

コメントを投稿

(いままで、ここでコメントしたことがないときは、コメントを表示する前にこのブログのオーナーの承認が必要になることがあります。承認されるまではコメントは表示されません。そのときはしばらく待ってください。)