Cloud FunctionsはAuthの次に大切な要素なのでじっくり勉強したいです
この記事はReact Firebase入門シリーズです
1-1-1・ Firebase初期設定とFirebaseAuthのSignUp
1-1-2・ 「react-hook-form」を入れてみた
1-1-3・ AuthのSignUpの通信エラー対応
1-2 ・ FirebaseAuthのログイン処理
1-3 ・ FirebaseAuthのログイン認証とログアウト処理
1-4 ・ FirebaseAuthのパスワード初期化処理
1-5 ・ FirebaseAuthのメールアドレスの有効化
1-6 ・ FirebaseAuthのメールアドレスとパスワード変更
1-7 ・ FirebaseAuthの表示名変更
1-8 ・ FirebaseAuthの拡張項目追加
1-9-1 ・ FirebaseAuthのTwitter認証
1-9-2 ・ FirebaseAuthのTwitter認証(既存ユーザー向け)と解除
1-10 ・ FirebaseAuthのGoogle認証(既存ユーザー含む)と解除
2-1・ FirebaseStorageのファイルアップ:基礎
2-2・ FirebaseStorageのファイルアップ前に画像の切り抜き
2-3・ FirebaseStorageのファイルアップの移動
3-1・FirestoreのCRUD
3-2・Firestoreのデータ取得補足
3-3・Firestoreのページネーション処理
3-4・Firestoreのコレクション(テーブル)のJOIN
5・ FirebaseのHosting(デプロイ)
6-1・ Cloud FunctionsでHello,world 今ここ
Cloud Functions for Firebase とは
Cloud FunctionsはFirebaseで実行できるAWS Lambdaみたいなです。 Firebaseが用意してくれている機能ではできない事もできます
例
- ユーザーが作成時にDB(FireStore)に書き込みする
- LinkedIn や Instagram などの認証プロバイダを使用してユーザーのログインを行います。
- FireStore 書き込みで webhook にリクエストを送信します。
- Realtime Database 書き込みで webhook にリクエストを送信します。
- Realtime Database 要素に対する全文検索を有効化します。
- ユーザーからの支払いを処理します。(Stripe)
Cloud Functionsが使えていないとFirebaseに入門できていない状況です。
無料->従量課金制
今まではFirebaseの無料の機能を使っていました(どれだけ使っても無料の枠で収まる)
Cloud Functionsは無料枠を使うだけでもプランを従量課金制に移行しないといけません。
クレジットカードなんて登録したくない人は、諦めるかカードを発行できるサービスなどを利用してください。
普通に使えば100円もいかないと思います。またアラートの設定もできるので気になる人は設定してください
1アカウントで従量課金制にできるアカウント数が10ぐらいなのでもし足りない場合はGoogle先生に拡張依頼をする形になります。
https://support.google.com/code/contact/billing_quota_increase?authuser=0
やりたい事
- Cloud Functionsを使ってHello,World
ツールのインストールと初期設定
hostingでやったのですが・・・一応は書きます。
Firebase-CLIの導入
以下のコマンドをターミナルで実行し、Firebase-CLIをインストールする。
(管理者権限で実行する)
$ npm install -g firebase-tools
Googleアカウントを紐づけ
$ firebase login
# 実行後、メールアドレスなどを入力する
Firebaseの初期化
プロジェクトFolderのルートに移動して以下を実行してFirebaseを初期化
$ cd ProjectFolder
$ firebase init
初期化後、以下のようにターミナルから、色々聞かれるので
######## #### ######## ######## ######## ### ###### ######## ## ## ## ## ## ## ## ## ## ## ## ###### ## ######## ###### ######## ######### ###### ###### ## ## ## ## ## ## ## ## ## ## ## ## #### ## ## ######## ######## ## ## ###### ######## ? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices. ( ) Database: Configure Firebase Realtime Database and deploy rules ( ) Firestore: Deploy rules and create indexes for Firestore > (*) Functions: Configure and deploy Cloud Functions ( ) Hosting: Configure and deploy Firebase Hosting sites ( ) Storage: Deploy Cloud Storage security rules ( ) Emulators: Set up local emulators for Firebase features ( ) Remote Config: Get, deploy, and rollback configurations for Remote Config
hostingの部分をスペースで選択してEnterキーを押します
◯ Functions: Configure and deploy Cloud Functions
を選択し、 スペースキー を押した後に Enter
次にoptionを聞かれるので
? Please select an option: > Use an existing project(既にProjectがある場合) Create a new project(Projectを新規作成) Add Firebase to an existing Google Cloud Platform project Don't set up a default project
Projectがあるので「Use an existing project」を選択します
? Select a default Firebase project for this directory: (Use arrow keys) > angular-study-chat (angular-study-chat) learn-firebase-masalib (Learn-Firebase-masalib) masalib-hosting (masalib-hosting) testpwa-32138 (testpwa)
Projectを選択してEnterキーを押します
=== Functions Setup A functions directory will be created in your project with a Node.js package pre-configured. Functions can be deployed with firebase deploy. ? What language would you like to use to write Cloud Functions? JavaScript JavaScript TypeScript
プログラムの言語を聞かれます。今どきのTypeScriptも選択できます。今回はJavaScriptを選択しました
? Do you want to use ESLint to catch probable bugs and enforce style? Yes #+ Wrote functions/package.json #+ Wrote functions/.eslintrc.json #+ Wrote functions/index.js #+ Wrote functions/.gitignore
ESLintをいれるのかと聞かれます。デプロイする時にチェックしてくれるのでYESにします
? Do you want to install dependencies with npm now? Yes #> protobufjs@6.10.2 postinstall D:\studypg\react\learn-firebase2\functions\node_modules\protobufjs #> node scripts/postinstall # #npm notice created a lockfile as package-lock.json. You should commit this file. #added 341 packages from 249 contributors and audited 341 packages in 20.393s #found 0 vulnerabilities # #i Writing configuration info to firebase.json... #i Writing project information to .firebaserc...
設定した内容のdependencies(依存関係)のパッケージをインストールしますかと聞かれます。 YESにします
#+ Firebase initialization complete!
初期設定が完了したとメッセージが表示されれば初期化は完了です
Firebaseの初期化終了後のフォルダ構成
project +- .firebaserc # Projectが記載されています。githubにはあげない方がいいかも | +- firebase.json # firebaseのツールの設定がはいります。以下の内容があります | # "functions": { | # "predeploy": [ | # "npm --prefix \"$RESOURCE_DIR\" run lint" | # ] | # } | +- functions/ # functions | +- .eslintrc.json # eslintの設定 | +- package.json # dependenciesや実行するための設定など | +- index.js # main source file このプログラムを修正してfunctionをつくります | +- node_modules/ # dependencies(依存関係)のパッケージ
プログラムの修正
おきまりのHello,Worldをしたいと思います。
const functions = require('firebase-functions'); exports.helloWorld = functions.https.onRequest((request, response) => { functions.logger.info("Hello World logs!", {structuredData: true}); response.send("Hello World"); })
デプロイ
$ firebase deploy --only functions #=== Deploying to 'learn-firebase-masalib'... #i deploying functions #Running command: npm --prefix "$RESOURCE_DIR" run lint #> functions@ lint D:\studypg\react\learn-firebase2\functions #> eslint . #+ functions: Finished running predeploy script. #i functions: ensuring required API cloudfunctions.googleapis.com is enabled... #i functions: ensuring required API cloudbuild.googleapis.com is enabled... #+ functions: required API cloudfunctions.googleapis.com is enabled #+ functions: required API cloudbuild.googleapis.com is enabled #i functions: preparing functions directory for uploading... #i functions: packaged functions (37.68 KB) for uploading #+ functions: functions folder uploaded successfully #i functions: updating Node.js 12 function helloWorld(region)... #+ functions[helloWorld(us-central1)]: Successful update operation. #+ Deploy complete! #Project Console: https://console.firebase.google.com/project/learn-firebase-masalib/overview
このログだとわかりにくいのですが URLは
https://<region>-<Project>.cloudfunctions.net/<function name>
になります
調べるのがめんどくさい人はコンソール上にURLが記載されます
確認
curlでURLを叩くと確認する事ができます(ちなみに下記のURLは無効なものです)
curl "https://region-learn-firebase-masalib.cloudfunctions.net/helloWorld" # Hello World
ログ確認はコンソール上でおこないます。
コマンドでも確認できます
firebase functions:log firebase functions:log --only <FUNCTION_NAME>
感想
Hello,Wolrdが簡単にできました。 公式のページはわかりにくい参考にしたページがわかりやすかった。 Firebaseの事しか書いてなくて・・・タイトルと違うwww。許してくださいgoogle先生