Cloud Functions for Firebase クライアント SDK を使用すると、Firebase アプリから関数を直接呼び出すことができます。この方法でアプリから関数を呼び出すには、Cloud Functions で HTTPS 呼び出し可能関数を作成してデプロイし、クライアント ロジックを追加してアプリから関数を呼び出します。
HTTPS 呼び出し可能関数は HTTP 関数と似ていますが、同一ではないことに注意してください。 HTTPS 呼び出し可能関数を使用するには、プラットフォーム用のクライアント SDK をfunctions.https
バックエンド API と共に使用する (またはプロトコルを実装する) 必要があります。 Callable には、HTTP 関数との次の重要な違いがあります。
- callable を使用すると、Firebase Authentication トークン、FCM トークン、および App Check トークンが利用可能な場合、自動的にリクエストに含まれます。
-
functions.https.onCall
トリガーは、リクエスト本文を自動的に逆シリアル化し、認証トークンを検証します。
Firebase SDK for Cloud Functions v0.9.1 以降は、これらの Firebase クライアント SDK の最小バージョンと相互運用して、HTTPS 呼び出し可能関数をサポートします。
- Apple プラットフォーム用 Firebase SDK 10.4.0
- Android 20.2.2 用 Firebase SDK
- Firebase JavaScript SDK 8.10.1
- Firebase Modular Web SDK v. 9.0
サポートされていないプラットフォームで構築されたアプリに同様の機能を追加する場合は、 https.onCall
のプロトコル仕様を参照してください。このガイドの残りの部分では、Apple プラットフォーム、Android、Web、C++、および Unity 用の HTTPS 呼び出し可能関数を作成、デプロイ、および呼び出す方法について説明します。
呼び出し可能な関数を作成してデプロイする
functions.https.onCall
を使用して、HTTPS 呼び出し可能関数を作成します。このメソッドは、 data
とオプションのcontext
の 2 つのパラメーターを取ります。
// Saves a message to the Firebase Realtime Database but sanitizes the text by removing swearwords.
exports.addMessage = functions.https.onCall((data, context) => {
// ...
});
たとえば、テキスト メッセージを Realtime Database に保存する呼び出し可能な関数の場合、 data
にはメッセージ テキストを含めることができ、 context
パラメータはユーザー認証情報を表します。
// Message text passed from the client.
const text = data.text;
// Authentication / user information is automatically added to the request.
const uid = context.auth.uid;
const name = context.auth.token.name || null;
const picture = context.auth.token.picture || null;
const email = context.auth.token.email || null;
呼び出し可能な関数の場所と呼び出し元のクライアントの場所の間の距離によって、ネットワークの待機時間が発生する可能性があります。パフォーマンスを最適化するには、必要に応じて関数の場所を指定することを検討し、クライアント側で SDK を初期化するときに設定された場所に callable の場所を合わせてください。
必要に応じて、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 the message.
return admin.database().ref('/messages').push({
text: sanitizedMessage,
author: { uid, name, picture, email },
}).then(() => {
console.log('New Message written');
// Returning the sanitized message to the client.
return { text: sanitizedMessage };
})
エラー処理
クライアントが有用なエラーの詳細を取得できるようにするには、 functions.https.HttpsError
のインスタンスをスローする (または拒否された Promise を返す) ことにより、callable からエラーを返します。エラーには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 functions.https.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 (!context.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
'while authenticated.');
}
呼び出し可能な関数をデプロイする
完成した呼び出し可能な関数をindex.js
内に保存すると、 firebase deploy
を実行すると、他のすべての関数と共にデプロイされます。 callable のみをデプロイするには、示されているように--only
引数を使用して部分的なデプロイを実行します。
firebase deploy --only functions:addMessage
関数のデプロイ時に権限エラーが発生した場合は、デプロイ コマンドを実行しているユーザーに適切なIAM ロールが割り当てられていることを確認してください。
クライアント開発環境をセットアップする
前提条件を満たしていることを確認してから、必要な依存関係とクライアント ライブラリをアプリに追加します。
iOS+
指示に従ってFirebase を Apple アプリに追加します。
Swift Package Manager を使用して、Firebase の依存関係をインストールおよび管理します。
- Xcode で、アプリ プロジェクトを開いた状態で、 File > Add Packagesに移動します。
- プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。
- Cloud Functions ライブラリを選択します。
- 完了すると、Xcode はバックグラウンドで依存関係の解決とダウンロードを自動的に開始します。
https://github.com/firebase/firebase-ios-sdk
Web version 9
- 指示に従ってFirebase を Web アプリに追加します。端末から次のコマンドを必ず実行してください:
npm install firebase@9.16.0 --save
Firebase コアと Cloud Functions の両方を手動で要求します。
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);
Web version 8
- 指示に従ってFirebase を Web アプリに追加します。
- Firebase コアと Cloud Functions クライアント ライブラリをアプリに追加します:
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-functions.js"></script>
Cloud Functions SDK は、npm パッケージとしても利用できます。
- 端末から次のコマンドを実行します:
npm install firebase@8.10.1 --save
- Firebase コアと Cloud Functions の両方を手動で要求する:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Kotlin+KTX
指示に従ってFirebase を Android アプリに追加します。
モジュール (アプリレベル) の 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:31.2.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 BoMを使用すると、アプリは常に互換性のあるバージョンの 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.2.2' }
Java
指示に従ってFirebase を Android アプリに追加します。
モジュール (アプリレベル) の 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:31.2.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 BoMを使用すると、アプリは常に互換性のあるバージョンの 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.2.2' }
Dart
指示に従ってFirebase を Flutter アプリに追加します。
Flutter プロジェクトのルートから、次のコマンドを実行してプラグインをインストールします。
flutter pub add cloud_functions
完了したら、Flutter アプリケーションを再構築します。
flutter run
インストールしたら、Dart コードにインポートして
cloud_functions
プラグインにアクセスできます。import 'package:cloud_functions/cloud_functions.dart';
C++
C++ と Androidの場合:
- 指示に従ってFirebase を C++ プロジェクトに追加します。
-
firebase_functions
ライブラリをCMakeLists.txt
ファイルに追加します。
Apple プラットフォームの C++ の場合:
- 指示に従ってFirebase を C++ プロジェクトに追加します。
- Cloud Functions ポッドを
Podfile
に追加します:pod 'Firebase/Functions'
- ファイルを保存して実行します:
pod install
- Firebase C++ SDKから Firebase コアと Cloud Functions フレームワークを Xcode プロジェクトに追加します。
-
firebase.framework
-
firebase_functions.framework
-
団結
- 指示に従ってFirebase を Unity プロジェクトに追加します。
- Firebase Unity SDKから
FirebaseFunctions.unitypackage
を Unity プロジェクトに追加します。
クライアント SDK を初期化する
Cloud Functions のインスタンスを初期化します。
迅速
lazy var functions = Functions.functions()
Objective-C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
Web version 8
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FUNCTIONS PROJECT ID ###'
databaseURL: 'https://### YOUR DATABASE NAME ###.firebaseio.com',
});
// Initialize Cloud Functions through Firebase
var functions = firebase.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();
Dart
final functions = FirebaseFunctions.instance;
C++
firebase::functions::Functions* functions;
// ...
functions = firebase::functions::Functions::GetInstance(app);
団結
functions = Firebase.Functions.DefaultInstance;
関数を呼び出す
迅速
functions.httpsCallable("addMessage").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
}
}
Objective-C
[[_functions HTTPSCallableWithName:@"addMessage"] callWithObject:@{@"text": _inputField.text}
completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
if (error) {
if ([error.domain isEqual:@"com.firebase.functions"]) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[@"details"];
}
// ...
}
self->_resultField.text = result.data[@"text"];
}];
Web version 8
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
Web version 9
import { getFunctions, httpsCallable } from "firebase/functions";
const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
/** @type {any} */
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 .getHttpsCallable("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 } }
Java
private Task<String> addMessage(String text) { // Create the arguments to the callable function. Map<String, Object> data = new HashMap<>(); data.put("text", text); data.put("push", true); return mFunctions .getHttpsCallable("addMessage") .call(data) .continueWith(new Continuation<HttpsCallableResult, String>() { @Override public String then(@NonNull Task<HttpsCallableResult> task) throws Exception { // This continuation runs on either success or failure, but if the task // has failed then getResult() will throw an Exception which will be // propagated down. String result = (String) task.getResult().getData(); return result; } }); }
Dart
final result =
await FirebaseFunctions.instance.httpsCallable('addMessage').call();
C++
firebase::Future<firebase::functions::HttpsCallableResult> AddMessage(
const std::string& text) {
// Create the arguments to the callable function.
firebase::Variant data = firebase::Variant::EmptyMap();
data.map()["text"] = firebase::Variant(text);
data.map()["push"] = true;
// Call the function and add a callback for the result.
firebase::functions::HttpsCallableReference doSomething =
functions->GetHttpsCallable("addMessage");
return doSomething.Call(data);
}
団結
private Task<string> addMessage(string text) {
// Create the arguments to the callable function.
var data = new Dictionary<string, object>();
data["text"] = text;
data["push"] = true;
// Call the function and extract the operation from the result.
var function = functions.GetHttpsCallable("addMessage");
return function.CallAsync(data).ContinueWith((task) => {
return (string) task.Result.Data;
});
}
クライアントでエラーを処理する
サーバーがエラーをスローした場合、または結果の promise が拒否された場合、クライアントはエラーを受け取ります。
関数によって返されたエラーのタイプがfunction.https.HttpsError
である場合、クライアントはサーバー エラーからエラーcode
、 message
、およびdetails
を受け取ります。それ以外の場合、エラーにはメッセージINTERNAL
とコードINTERNAL
が含まれます。呼び出し可能な関数でエラーを処理する方法については、ガイダンスを参照してください。
迅速
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]
}
// ...
}
Objective-C
if (error) {
if ([error.domain isEqual:@"com.firebase.functions"]) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[@"details"];
}
// ...
}
Web version 8
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
})
.catch((error) => {
// Getting the Error details.
var code = error.code;
var message = error.message;
var details = error.details;
// ...
});
Web version 9
import { getFunctions, httpsCallable } from "firebase/functions";
const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
/** @type {any} */
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 } } }
Java
addMessage(inputMessage) .addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { if (!task.isSuccessful()) { Exception e = task.getException(); if (e instanceof FirebaseFunctionsException) { FirebaseFunctionsException ffe = (FirebaseFunctionsException) e; FirebaseFunctionsException.Code code = ffe.getCode(); Object details = ffe.getDetails(); } } } });
Dart
try {
final result =
await FirebaseFunctions.instance.httpsCallable('addMessage').call();
} on FirebaseFunctionsException catch (error) {
print(error.code);
print(error.details);
print(error.message);
}
C++
void OnAddMessageCallback(
const firebase::Future<firebase::functions::HttpsCallableResult>& future) {
if (future.error() != firebase::functions::kErrorNone) {
// Function error code, will be kErrorInternal if the failure was not
// handled properly in the function call.
auto code = static_cast<firebase::functions::Error>(future.error());
// Display the error in the UI.
DisplayError(code, future.error_message());
return;
}
const firebase::functions::HttpsCallableResult* result = future.result();
firebase::Variant data = result->data();
// This will assert if the result returned from the function wasn't a string.
std::string message = data.string_value();
// Display the result in the UI.
DisplayResult(message);
}
// ...
// ...
auto future = AddMessage(message);
future.OnCompletion(OnAddMessageCallback);
// ...
団結
addMessage(text).ContinueWith((task) => {
if (task.IsFaulted) {
foreach (var inner in task.Exception.InnerExceptions) {
if (inner is FunctionsException) {
var e = (FunctionsException) inner;
// Function error code, will be INTERNAL if the failure
// was not handled properly in the function call.
var code = e.ErrorCode;
var message = e.ErrorMessage;
}
}
} else {
string result = task.Result;
}
});
推奨: App Check で不正使用を防止
アプリを起動する前に、 App Checkを有効にして、自分のアプリだけが呼び出し可能な関数のエンドポイントにアクセスできるようにする必要があります。