firebase関数pt 1の開発-初期化と配備


最近、私はGoogle Firebaseの起動を開始し、比較的簡単な展開パイプラインのオーバーヘッドのためにつまらない.特に、NodeJSコードとHTTPSのためのそのサポートは、API開発とa low-cost option . この記事では、NodeJS APIを起動してテストを行うことができます.

インストールと初期設定


起動するには、FireBaseのCLIがコンピュータにインストールされていることを確認します.FireBase CLIをインストールするにはthese instructions . 完了したら、FireBaseバージョン8.6.0をインストールしていることを確認します.
$ firebase --version 
8.6.0
バージョン8.6.0をインストールしていない場合は、NPMで次のコマンドを使用してこのバージョンをグローバルにインストールできます.
$ npm install -g [email protected]
$ npm install -g [email protected]
注意: EAccessを受信した場合は、NPMのインストールコマンドを実行している許可を受けません.sudo npm install... 代わりに.
今、頭をFirebase そしてサイン入り.前にFireBaseを使用したことがない場合は、すべての必要なGoogleアカウントにログインすることです.
FireBase CLIを使用して、コマンドラインアプリケーションを使用してFireBaseアカウントにログインします.
$ firebase login

? Allow Firebase to collect CLI usage and error reporting information (Y/n): N
これは、あなたのブラウザにあるページを開き、あなたのアカウントにアクセスするために、FireBaseとGriの許可をログインします.署名したら、CLIに資格情報が格納され、プロジェクトを初期化する準備が整いました.
新しいフォルダを作成し、コマンドラインアプリケーションを使用してこのフォルダを参照してください.次に、スクリプトを使用して初期化を開始します.
$ firebase init
このコマンドが入力されると、作成したいプロジェクトの種類をプロンプトが表示されます.このチュートリアルでは、関数プロジェクトのみを作成します.矢印キーを使用して、関数に移動し、スペースをヒットし、Enterキーを押します.次に、新しいプロジェクトを作成するか、既存のプロジェクトを使用するかどうかを尋ねます.「新規プロジェクトを作成」を選択し、ユニークなプロジェクト名を指定します(名前がすでに取られている場合は初期化は失敗します).その後、プロジェクトを呼び出すために名前を選択します(空白の場合は、プロジェクト名にデフォルトになります).
次に、JavaScriptまたはTypeScriptを使用するかどうかを尋ねます.このプロジェクトのJavaScriptを使用します.次に、ESLINTを使用して、バグや実行スタイルをキャッチしたい場合は、NPMとの依存関係をインストールする場合は、「いいえ」を選択してください.
$ firebase init

You're about to initialize a Firebase project in this directory:

  /Users/matt/Documents/test

? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices. Functions
: Configure and deploy Cloud Functions

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add, 
but for now we'll just set up a default project.

? Please select an option: Create a new project
i  If you want to create a project in a Google Cloud organization or folder, please use "firebase projects:create" instead, and return to this command when you've created the project.
? Please specify a unique project id (warning: cannot be modified afterwa
rd) [6-30 characters]:
 irbytestproject
? What would you like to call your project? (defaults to your project ID)

✔ Creating Google Cloud Platform project
✔ Adding Firebase resources to Google Cloud Platform project

🎉🎉🎉 Your Firebase project is ready! 🎉🎉🎉

Project information:
   - Project ID: irbytestproject
   - Project Name: irbytestproject

Firebase console is available at
https://console.firebase.google.com/project/irbytestproject/overview
i  Using project irbytestproject (irbytestproject)

=== 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
? Do you want to use ESLint to catch probable bugs and enforce style? No
✔  Wrote functions/package.json
✔  Wrote functions/index.js
✔  Wrote functions/.gitignore
? Do you want to install dependencies with npm now? Yes

added 255 packages, and audited 256 packages in 5s

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...
i  Writing gitignore file to .gitignore...

プロジェクトフォルダの内部では、フォルダfunctions . あなたがパッケージをチェックするならば.このフォルダ内のJSONファイルには、以下のような非常によく似たものがあります.
{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "10"
  },
  "dependencies": {
    "firebase-admin": "^8.10.0",
    "firebase-functions": "^3.6.1"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}
いくつかの項目に注意してください.まず、コマンドなどが表示されますfirebase emulators:start and firebase deploy . これらのコマンドは、ローカルにあなたの関数を実行し、関数を展開できるようになります.The --only functions これらのコマンドの最後のフラグは、機能フォルダをFirebaseに配備するだけであることを指定します.

ローカルのAPIの実行


我々のAPIを走らせて、それが若干の仕事をするのを見ましょう.エミュレータを起動するには、次のコマンドを実行します.
$ firebase emulators:start

i  emulators: Starting emulators: functions
⚠  functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: firestore, database, hosting, pubsub
⚠  Your requested "node" version "10" doesn't match your global version "12"
i  ui: Emulator UI logging to ui-debug.log
i  functions: Watching "/Users/matt/Documents/test/functions" for Cloud Functions...

┌───────────────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! View status and logs at http://localhost:4000 │
└───────────────────────────────────────────────────────────────────────┘

┌───────────┬────────────────┬─────────────────────────────────┐
│ Emulator  │ Host:Port      │ View in Emulator UI             │
├───────────┼────────────────┼─────────────────────────────────┤
│ Functions │ localhost:5001 │ http://localhost:4000/functions │
└───────────┴────────────────┴─────────────────────────────────┘
  Other reserved ports: 4400, 4500
さて、エミュレータがどのように設定されているかによって、ホストボックスに異なる値が表示されます.私の例では、私はlocalhostを持っています.訪問する時http://localhost:5001 ブラウザでは、次のようなメッセージが表示されます.
Cannot GET /
これは私のAPIがアクティブであるということですが、私が到達しようとしているエンドポイントは入手できません.プロジェクトを見てみましょう.
関数のフォルダ内で、パッケージに加えて.JSONファイルには別のファイルがありますindex.js . インデックス.jsファイルはAPIのエントリポイントとして機能します.私がインデックスを開くとき.jsファイルは次のようになります.
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) => {
//   functions.logger.info("Hello logs!", {structuredData: true});
//   response.send("Hello from Firebase!");
// });

気がかりなことが二つあります.まず最初に、一番上に、firebase機能パッケージがあります.二つ目は、以下のコードがコメントアウトされていることです.
FireBase関数パッケージは、FireBase用のクラウド関数へのアクセスを提供するSDKです.それはあなたが環境変数(我々は次のポストでさらに見て)とHTTPルートを定義するようなものにアクセスすることができます.
コメントアウトコードでは、エンドポイントをエクスポートするコマンドがありますhelloWorld , そして、HTTPリクエストをログにする関数に送る機能コマンドを指し示していますHello logs! そして戻って応答を送信するHello from Firebase! .
このコードをコメントしてみましょう.
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) => {
  functions.logger.info("Hello logs!", {structuredData: true});
  response.send("Hello from Firebase!");
});
エミュレータが実行されている間、それは任意の保存された変更を検出し、自動的にプロジェクトを再読み込みします.コマンドラインをチェックすると、次のメッセージが表示されます
functions[helloWorld]: http function initialized (http://localhost:5001/irbytestproject/us-central1/helloWorld).
ブラウザでURLを訪問すると、「Firebaseからこんにちは」というプレーンHTMLページがあります.きちんと!私のAPIは働いている!
では、ログコマンドが捕捉されたかどうかを確認してください.
i  functions: Beginning execution of "helloWorld"
>  {"structuredData":true,"severity":"INFO","message":"Hello logs!"}
i  functions: Finished "helloWorld" in ~1s
APIが動作し、ログが捕捉されているのを見ることができるようになりました.APIの展開に移りましょう.

APIの配備


今ではあまりないが、我々は進歩したことを誇りに思うべきだ.私は、世界が我々の創造を見る準備ができていると思います.
エミュレータを停止しましょうfirebase deploy コマンド.我々のプロジェクトには機能があるだけで、我々は--only functions フラグ.
$ firebase deploy


=== Deploying to 'irbytestproject'...

i  deploying functions
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: missing required API cloudbuild.googleapis.com. Enabling now...

Error: HTTP Error: 400, Billing account for project [removed] is not found. Billing must be enabled for activation of service(s) 'cloudbuild.googleapis.com,containerregistry.googleapis.com' to proceed.
Help Token: ...
我々のプロジェクトがまだ課金のためのセットアップでないので、我々が問題に走らせたように見えます.問題ありません.これを修正するには、訪問してコンソールに行きましょうhttps://console.firebase.google.com/ , プロジェクトに行き、関数をクリックしてUpgrade project .

選択Blaze - Pay as You Go オプションは、あなたの請求情報を入力し、購入.
これが完了すると、我々は再び展開コードを実行する準備が整いました.プロジェクトのアップグレードが効果を発揮するには数分かかるかもしれませんし、展開が初めての場合は特に数分かかるかもしれません.
$ firebase deploy

=== Deploying to 'irbytestproject'...

i  deploying functions
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
⚠  functions: missing required API cloudbuild.googleapis.com. Enabling now...
✔  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 (54.5 KB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: creating Node.js 10 function helloWorld(us-central1)...
✔  functions[helloWorld(us-central1)]: Successful create operation. 
Function URL (helloWorld): https://us-central1-irbytestproject.cloudfunctions.net/helloWorld

✔  Deploy complete!
さて、firebase関数ページをもう一度チェックするなら、HelloWorldの関数エントリを見ることができます.

我々のAPIをテストしましょう!関数のURLをコピーしてブラウザに入れます.プレーンHTMLページが表示されますHello from Firebase!

結論


FireBase機能プロジェクトを初期化し、ローカルで実行し、FireBaseに配備しました.ここでは、環境変数を作成したり、POSTやPUTなどの異なるHTTPメソッドを扱うなどの概念を歩きます.