アプリから関数を呼び出す

Cloud Functions for Firebase のクライアント SDK を使用すると、Firebase アプリから関数を直接呼び出すことができます。この方法でアプリから関数を呼び出すには、Cloud Functions において HTTPS 呼び出し可能関数を記述してデプロイし、アプリから関数を呼び出すためのクライアント ロジックを追加します。

HTTPS 呼び出し可能関数は HTTP 関数と類似しているものの、同一ではないことに注意することが重要です。また、第 1 世代と第 2 世代の関数ではコールバック署名が異なります。

// Adds two numbers to each other.
exports.addnumbers = onCall((request) => {
  // Numbers passed from the client.
  const firstNumber = request.data.firstNumber;
  const secondNumber = request.data.secondNumber;

  // Checking that attributes are present and are numbers.
  if (!Number.isFinite(firstNumber) || !Number.isFinite(secondNumber)) {
    // Throwing an HttpsError so that the client gets the error details.
    throw new HttpsError("invalid-argument", "The function must be called " +
            "with two arguments \"firstNumber\" and \"secondNumber\" which " +
            "must both be numbers.");
  }

  // returning result.
  return {
    firstNumber: firstNumber,
    secondNumber: secondNumber,
    operator: "+",
    operationResult: firstNumber + secondNumber,
  };
});

呼び出し可能関数と HTTP 関数の主な違いは以下のとおりです。

  • 呼び出し可能関数では、Firebase Authentication トークン、FCM トークン、App Check トークンが利用可能な場合、自動的にリクエストに追加されます。
  • functions.https.onCall トリガーは、リクエスト本文を自動的に逆シリアル化し、認証トークンを検証します。

Firebase SDK for Cloud Functions(第 2 世代)以降は、次の各 Firebase クライアント SDK の最小バージョンとの連携によって、HTTPS 呼び出し可能関数をサポートします。

  • Firebase SDK for Apple platforms 10.9.0
  • Firebase SDK for Android 20.3.0
  • Firebase Modular Web SDK v. 9.7.0

サポートされていないプラットフォーム上で構築されたアプリに同様の機能を追加する場合は、https.onCall のプロトコル仕様を参照してください。これ以降は、Apple プラットフォーム、Android、ウェブ、C++、Unity 用の HTTPS 呼び出し可能関数の記述、デプロイ、呼び出し方法について説明します。

呼び出し可能関数の記述とデプロイ

HTTP 呼び出し可能関数を作成するには、functions/v2/https サブパッケージの onCall メソッドを使用します。このメソッドの event パラメータに、dataauthappinstanceToken プロパティを指定します。

// Saves a message to the Firebase Realtime Database but sanitizes the
// text by removing swearwords.
exports.addmessage = onCall((request) => {
  // ...
});

たとえば、Realtime Database にテキスト メッセージを保存する呼び出し可能関数の場合、data にメッセージ テキストを指定し、auth に認証情報を指定できます。

// Message text passed from the client.
const text = request.data.text;
// Authentication / user information is automatically added to the request.
const uid = request.auth.uid;
const name = request.auth.token.name || null;
const picture = request.auth.token.picture || null;
const email = request.auth.token.email || null;

呼び出し可能関数のロケーションと呼び出し側のクライアントのロケーションが離れている場合、ネットワーク レイテンシが発生する可能性があります。パフォーマンスを最適化するには、適切な場所に関数のロケーションを指定し、クライアントサイドで SDK を初期化するときに、設定されたロケーションに応じて呼び出し可能関数のロケーションを調整します。

必要に応じて、App Check 証明書を添付して、請求詐欺やフィッシングなどの不正行為からバックエンド リソースを保護することができます。Cloud Functions に対して App Check の適用を有効にするをご覧ください。

結果を返送する

クライアントにデータを返送するには、JSON でエンコード可能なデータを返します。たとえば、加法演算の結果を返すには、次のように使用します。

// returning result.
return {
  firstNumber: firstNumber,
  secondNumber: secondNumber,
  operator: "+",
  operationResult: firstNumber + secondNumber,
};

非同期オペレーションの後にデータを返すには、Promise を返します。Promise によって返されたデータは、クライアントに返送されます。たとえば、呼び出し可能関数が Realtime Database に書き込んだサニタイズ済みのテキストを返すことができます。

// Saving the new message to the Realtime Database.
const sanitizedMessage = sanitizer.sanitizeText(text); // Sanitize message.

return getDatabase().ref("/messages").push({
  text: sanitizedMessage,
  author: {uid, name, picture, email},
}).then(() => {
  logger.info("New Message written");
  // Returning the sanitized message to the client.
  return {text: sanitizedMessage};
})

エラーを処理する

有用なエラーの詳細をクライアントで取得できるようにするには、functions.https.HttpsError のインスタンスをスローする(またはこのインスタンスで拒否された Promise を返す)ことにより、呼び出し可能関数からエラーを返します。エラーの code 属性は、functions.https.HttpsError に示されているいずれかの値を取ることができます。エラーには文字列 message も含まれています。デフォルトは空の文字列です。エラーでは、オプションの details フィールドに任意の値を設定することもできます。関数から HttpsError 以外のエラーがスローされると、クライアントでは代わりにメッセージ INTERNAL とコード internal が含まれるエラーを受け取ります。

たとえば、関数はデータ検証や認証に関するエラーをスローすることができますが、その際に呼び出し元のクライアントに返すエラー メッセージを付加することができます。

// Checking attribute.
if (!(typeof text === "string") || text.length === 0) {
  // Throwing an HttpsError so that the client gets the error details.
  throw new HttpsError("invalid-argument", "The function must be called " +
          "with one arguments \"text\" containing the message text to add.");
}
// Checking that the user is authenticated.
if (!request.auth) {
  // Throwing an HttpsError so that the client gets the error details.
  throw new HttpsError("failed-precondition", "The function must be " +
          "called while authenticated.");
}

呼び出し可能関数をデプロイする

完成した呼び出し可能関数を index.js 内に保存した後、firebase deploy を実行すると、他のすべての関数とともにデプロイされます。呼び出し可能関数のみをデプロイするには、次に示すように --only 引数を使用して部分デプロイを行います。

firebase deploy --only functions:addMessage

関数のデプロイ時に権限エラーが発生した場合は、デプロイ コマンドを実行するユーザーに適切な IAM ロールが割り当てられていることを確認します。

クライアント開発環境を設定する

すべての前提条件を満たしていることを確認し、必要な依存関係とクライアント ライブラリをアプリに追加します。

iOS+

Firebase を Apple アプリに追加するの手順に沿って操作します。

Swift Package Manager を使用して Firebase の依存関係のインストールと管理を行います。

  1. Xcode でアプリのプロジェクトを開いたまま、[File] > [Add Packages] の順に移動します。
  2. プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。
  3.   https://github.com/firebase/firebase-ios-sdk
  4. Cloud Functions ライブラリを選択します。
  5. 上記の作業が完了すると、Xcode は依存関係の解決とダウンロードをバックグラウンドで自動的に開始します。

Web version 9

  1. Firebase をウェブアプリに追加するの手順に沿って操作します。ターミナルから次のコマンドを実行します。
    npm install firebase@9.21.0 --save
    
  2. Firebase Core と Cloud Functions の両方を手動で require します。

     import { initializeApp } from 'firebase/app';
     import { getFunctions } from 'firebase/functions';
    
     const app = initializeApp({
         projectId: '### CLOUD FUNCTIONS PROJECT ID ###',
         apiKey: '### FIREBASE API KEY ###',
         authDomain: '### FIREBASE AUTH DOMAIN ###',
       });
     const functions = getFunctions(app);
    

Kotlin+KTX

  1. Android アプリに Firebase を追加するの手順に沿って操作します。

  2. モジュール(アプリレベル)の Gradle ファイル(通常は <project>/<app-module>/build.gradle)に、Cloud Functions Android ライブラリの依存関係を追加します。ライブラリのバージョニングの制御には、Firebase Android 部品構成表(BoM)を使用することをおすすめします。

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.0.0')
    
        // Add the dependency for the Cloud Functions library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-functions-ktx'
    }
    

    Firebase Android 部品構成表を使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。

    (代替方法)BoM を使用せずに Firebase ライブラリの依存関係を追加する

    Firebase BoM を使用しない場合は、依存関係の行でそれぞれの Firebase ライブラリのバージョンを指定する必要があります。

    アプリで複数の Firebase ライブラリを使用する場合は、すべてのバージョンの互換性を確保するため、BoM を使用してライブラリのバージョンを管理することを強くおすすめします。

    dependencies {
        // Add the dependency for the Cloud Functions library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-functions-ktx:20.3.0'
    }
    

Java

  1. Android アプリに Firebase を追加するの手順に沿って操作します。

  2. モジュール(アプリレベル)の Gradle ファイル(通常は <project>/<app-module>/build.gradle)に、Cloud Functions Android ライブラリの依存関係を追加します。ライブラリのバージョニングの制御には、Firebase Android 部品構成表(BoM)を使用することをおすすめします。

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.0.0')
    
        // Add the dependency for the Cloud Functions library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-functions'
    }
    

    Firebase Android 部品構成表を使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。

    (代替方法)BoM を使用せずに Firebase ライブラリの依存関係を追加する

    Firebase BoM を使用しない場合は、依存関係の行でそれぞれの Firebase ライブラリのバージョンを指定する必要があります。

    アプリで複数の Firebase ライブラリを使用する場合は、すべてのバージョンの互換性を確保するため、BoM を使用してライブラリのバージョンを管理することを強くおすすめします。

    dependencies {
        // Add the dependency for the Cloud Functions library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-functions:20.3.0'
    }
    

クライアント SDK を初期化する

Cloud Functions のインスタンスを初期化します。

Swift

lazy var functions = Functions.functions()

Objective-C

@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];

Web version 9

const app = initializeApp({
  projectId: '### CLOUD FUNCTIONS PROJECT ID ###',
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
});
const functions = getFunctions(app);

Kotlin+KTX

private lateinit var functions: FirebaseFunctions
// ...
functions = Firebase.functions

Java

private FirebaseFunctions mFunctions;
// ...
mFunctions = FirebaseFunctions.getInstance();

関数を呼び出す

Swift

let addMessageURL = URL(string: "https://addmessage-xyz1234-uc.a.run.app/addMessage")!

functions.httpsCallable(addMessageURL).call(["text": inputField.text]) { result, error in
  if let error = error as NSError? {
    if error.domain == FunctionsErrorDomain {
      let code = FunctionsErrorCode(rawValue: error.code)
      let message = error.localizedDescription
      let details = error.userInfo[FunctionsErrorDetailsKey]
    }
    // ...
  }
  if let data = result?.data as? [String: Any], let text = data["text"] as? String {
    self.resultField.text = text
  }
}

Web version 9

import { getFunctions, httpsCallableFromURL } from 'firebase/functions';

const functions = getFunctions();
const addMessage = httpsCallableFromURL(
  functions,
  // the URL of the function
  "https://addmessage-xyz1234-uc.a.run.app/addMessage"
);

addMessage({ text: messageText })
  .then((result) => {
    // Read result of the Cloud Function.
    const data = result.data;
    const sanitizedMessage = data.text;
  });

Kotlin+KTX

private fun addMessage(text: String): Task<String> {
    // Create the arguments to the callable function.
    val data = hashMapOf(
        "text" to text,
        "push" to true
    )

    return functions
            // The URL of the function
            .getHttpsCallableFromUrl(URL("https://addmessage-xyz1234-uc.a.run.app/addMessage"))
            .call(data)
            .continueWith { task ->
                // This continuation runs on either success or failure, but if the task
                // has failed then result will throw an Exception which will be
                // propagated down.
                val result = task.result?.data as String
                result
            }
}

クライアントでエラーを処理する

サーバーがエラーをスローした場合、または結果の Promise が拒否された場合、クライアントはエラーを受け取ります。関数から返されたエラーの型が function.https.HttpsError の場合、クライアントにはサーバーエラーからエラーの codemessagedetails が出力されます。それ以外の場合、エラーにはメッセージ INTERNAL とコード INTERNAL が組み込まれます。呼び出し可能関数でエラーを処理する方法については、ガイダンスをご覧ください。

Swift

if let error = error as NSError? {
  if error.domain == FunctionsErrorDomain {
    let code = FunctionsErrorCode(rawValue: error.code)
    let message = error.localizedDescription
    let details = error.userInfo[FunctionsErrorDetailsKey]
  }
  // ...
}

Web version 9

import { getFunctions, httpsCallableFromURL } from "firebase/functions";

const functions = getFunctions();
const addMessage = httpsCallableFromURL(
  functions,
  // the URL of the function
  "https://addmessage-xyz1234-uc.a.run.app/addMessage"
);

addMessage({ text: messageText })
  .then((result) => {
    // Read result of the Cloud Function.
    const data = result.data;
    const sanitizedMessage = data.text;
  })
  .catch((error) => {
    // Getting the Error details.
    const code = error.code;
    const message = error.message;
    const details = error.details;
    // ...
  });

Kotlin+KTX

addMessage(inputMessage)
    .addOnCompleteListener { task ->
        if (!task.isSuccessful) {
            val e = task.exception
            if (e is FirebaseFunctionsException) {
                val code = e.code
                val details = e.details
            }
        }
    }

アプリをリリースする前に、App Check を有効にして、自分のアプリだけが呼び出し可能関数のエンドポイントにアクセスできるようにすることをおすすめします。