LoginSignup
3
2

More than 3 years have passed since last update.

【Firebase】Cloud FunctionsでHello world

Posted at

本稿では、Cloud Functions for Firebaseを利用してHello worldを返すエンドポイントを実装します。
基本的には公式のチュートリアルに従います。

環境

  • GCPプロジェクトを作成済み
  • Node v10.19.0

Firebase CLIのインストール

$ npm install firebase-functions@latest firebase-admin@latest --save
$ npm install -g firebase-tools

Firebase SDK for Cloud Functionsの初期化

Firebaseツールを認証する。

$ firebase login

Firebaseプロジェクトルートに移動し、空のプロジェクトを作成する。

$ firebase init functions

Firebaseが紐づくGCPプロジェクトを決める方法を選択する。
今回は既にGCPが存在する想定のため、Use an existing projectを選択する。

? Please select an option: 
❯ Use an existing project 
  Create a new project 
  Add Firebase to an existing Google Cloud Platform project 
  Don't set up a default project 

Firebaseのプロジェクトを選択する。

? Select a default Firebase project for this directory: 
❯ hogehoge (hogehoge) 
  fugafuga (fugafuga) 

言語をJSかTSから選択できる。今回はJSを選択する。

? What language would you like to use to write Cloud Functions? 
❯ JavaScript 
  TypeScript 

ESLint使うか選択する。

? Do you want to use ESLint to catch probable bugs and enforce style?
N

依存関係をインストールするか選択する。

?  Do you want to install dependencies with npm now?
Y

全ての質問に答え終わると、空のプロジェクトができます。

Hello world

セットアップを終えると、package.jsonindex.jsが作成されていると思います。

package.jsonのenginesを8から10に書き換えます。
(今回はHello worldだけなので、デフォルトの8でも大丈夫です。)

  "engines": {
    "node": "10"
  }

index.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) => {
 response.send("Hello from Firebase!");
});

デプロイする。

$ firebase deploy --only functions

GCPコンソールから詳細を確認することができます。
a.png

https://us-central1-hogehoge.cloudfunctions.net/helloWorld にアクセスすると...
(hogehogeはGCPのプロジェクトID)

b.png

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