LoginSignup
3
2

More than 3 years have passed since last update.

CloudFunctionをデプロイするための備忘録

Last updated at Posted at 2020-04-24

はじめに

CloudFunctionをデプロイする際に少々苦戦したので、備忘録として書き記しておきたいと思います。

CloudFunctionとは?

サーバーレスフレームワークで、Firebase の機能と HTTPS リクエストによってトリガーされたイベントに応じて、バックエンド コードを自動的に実行できます(公式より)

下準備

①Firebaseプロジェクトを作成 ※省略

②Node.js と Firebase CLI を設定する
該当プロジェクトのソースコードのディレクトに対して、ターミナルから

npm install -g firebase-tools

を実行。プロジェクトにfirebaseコマンドがインストールされます。

③FIrebaseにログインをする

firebase login

プロジェクトを作成したアカウント、あるいはコラボレートしているGoogleアカウントでログインします。

④functionの初期化をする

firebase init functions

JavaScriptあるいはTypescriptの選択、その他細かい設定を行えます。
成功すると、下記のような構造が新たに生成されます。

//公式より(https://firebase.google.com/docs/functions/get-started?hl=ja)
myproject
 +- .firebaserc    # Hidden file that helps you quickly switch between
 |                 # projects with `firebase use`
 |
 +- firebase.json  # Describes properties for your project
 |
 +- functions/     # Directory containing all your functions code
      |
      +- .eslintrc.json  # Optional file containing rules for JavaScript linting.
      |
      +- package.json  # npm package file describing your Cloud Functions code
      |
      +- index.js      # main source file for your Cloud Functions code
      |
      +- node_modules/ # directory where your dependencies (declared in
                       # package.json) are installed

functionのディレクトリの中の、index.jsに実行する関数を記述します。

⑤必要なモジュールのインポート
私の場合はユーザーの退会処理を行いたかったため、Authenticationに対応するAdminSDKをインポートした上で、利用のためにファイル内で初期化をしています(初期化をしないと動かない)

// 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();

⑥index.js内に実行したい関数を記述 ※本記事では省略。
関数をexportすることを忘れないようにしましょう。

デプロイする

※必ずfunctionsのディレクトリ内で実行する(筆者は恥ずかしながらこれを見落としていて、1時間くらい何度もfirebase initをやり直していました😅)

全ての関数をデプロイ
$ firebase deploy --only functions
指定した関数をデプロイ
$ firebase deploy --only functions:hogeFunction,functions:fooFunction
//index.jsに記載のhogeFunctionとfooFunctionがデプロイされます
指定した関数をFirebase上から削除(一度に複数削除するときはhogeFunctionの後に並べる)
$ firebase functions:delete hogeFunction

おわりに

使い方に慣れるまで少し時間がかかりますが、重要情報の処理をFirebaseに預けることで安心感がありますし、データベースもスムーズに更新されるためとても使い勝手が良い印象を受けました。引き続きFirebaseを使った開発を楽しみたいと思います!

●参考にしました!
CloudFunctionの下準備
CloudFunctionのデプロイ

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2