Cloud Functions for Firebase istemci SDK'ları, işlevleri doğrudan bir Firebase uygulamasından çağırmanıza olanak tanır. Uygulamanızdan bu şekilde bir işlevi çağırmak için, Cloud Functions'a bir HTTPS Çağrılabilir işlevi yazın ve dağıtın ve ardından işlevi uygulamanızdan çağırmak için istemci mantığı ekleyin.
HTTPS çağrılabilir işlevlerinin benzer olduğunu ancak HTTP işlevleriyle aynı olmadığını unutmamak önemlidir. HTTPS çağrılabilir işlevlerini kullanmak için, functions.https
arka uç API'si ile birlikte platformunuz için istemci SDK'sını kullanmanız (veya protokolü uygulamanız gerekir). Çağrılabilirler, HTTP işlevlerinden şu temel farklara sahiptir:
- Çağrılabilir özelliklerle Firebase Authentication ve FCM jetonları, mevcut olduğunda otomatik olarak isteklere dahil edilir.
-
functions.https.onCall
tetikleyicisi, istek gövdesinin serisini otomatik olarak kaldırır ve kimlik doğrulama belirteçlerini doğrular.
Cloud Functions v0.9.1 için Firebase SDK ve üzeri, HTTPS Çağrılabilir işlevlerini desteklemek için bu Firebase istemci SDK'sı minimum sürümleriyle birlikte çalışır:
- İOS 7.7.0 için Firebase SDK
- Android 19.2.0 için Firebase SDK
- Firebase JavaScript SDK 8.2.10
Desteklenmeyen bir platform üzerine kurulu bir uygulamaya benzer işlevsellik eklemek istiyorsanız, https.onCall
için Protokol Belirtimine https.onCall
. Bu kılavuzun geri kalanı, iOS, Android, web, C ++ ve Unity için bir HTTPS çağrılabilir işlevinin nasıl yazılacağı, dağıtılacağı ve çağrılacağı hakkında talimatlar sağlar.
Çağrılabilir işlevi yazın ve konuşlandırın
HTTPS çağrılabilir bir işlev oluşturmak için functions.https.onCall
kullanın. Bu yöntem iki parametre alır: data
ve isteğe bağlı context
:
// Saves a message to the Firebase Realtime Database but sanitizes the text by removing swearwords.
exports.addMessage = functions.https.onCall((data, context) => {
// ...
});
Örneğin, Gerçek Zamanlı Veritabanına bir metin mesajı kaydeden çağrılabilir bir işlev için, data
mesaj metnini içerebilirken, context
parametreleri kullanıcı kimlik doğrulama bilgilerini temsil eder:
// 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;
Çağrılabilir işlevin konumu ile arayan istemcinin konumu arasındaki mesafe, ağ gecikmesi yaratabilir. Performansı optimize etmek için, uygun olan yerlerde işlev konumunu belirtmeyi düşünün ve istemci tarafında SDK'yı başlattığınızda çağrılabilir konumun konum kümesiyle hizalandığından emin olun.
Sonucu geri gönderme
Verileri istemciye geri göndermek için JSON olarak kodlanabilen verileri döndürün. Örneğin, bir toplama işleminin sonucunu döndürmek için:
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: '+',
operationResult: firstNumber + secondNumber,
};
Eşzamansız bir işlemden sonra veri döndürmek için bir söz verin. Sözün getirdiği veriler müşteriye geri gönderilir. Örneğin, çağrılabilir işlevin Gerçek Zamanlı Veritabanına yazdığı temizlenmiş metni döndürebilirsiniz:
// 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 };
})
Hataları işleme
İstemcinin yararlı hata ayrıntılarını almasını sağlamak için, functions.https.HttpsError
örneğini atarak (veya reddedilen bir Promise döndürerek) bir çağrılabilir dosyadan hataları döndürür. Hatanın, functions.https.HttpsError
listelenen değerlerden biri olabilen bir code
özniteliği vardır. Hataların ayrıca varsayılan olarak boş bir dizeye dönüşen bir dize message
vardır. Ayrıca keyfi bir değere sahip isteğe bağlı bir details
alanına da sahip olabilirler. HttpsError
dışında bir hata HttpsError
, istemciniz INTERNAL
mesajı ve internal
kodu içeren bir hata alır.
Örneğin, bir işlev, arayan istemciye geri dönmek için hata mesajlarıyla birlikte veri doğrulama ve kimlik doğrulama hataları atabilir:
// 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.');
}
Çağrılabilir işlevi konuşlandırın
Tamamlanmış bir çağrılabilir işlevi index.js
içinde kaydettikten sonra, firebase deploy
çalıştırdığınızda diğer tüm işlevlerle birlikte firebase deploy
. Yalnızca çağrılabilir --only
dağıtmak için --only
argümanını gösterildiği gibi kullanarak kısmi --only
gerçekleştirin:
$ firebase deploy --only functions:addMessage
İşlevleri dağıtırken izin hatalarıyla karşılaşırsanız, dağıtım komutlarını çalıştıran kullanıcıya uygun IAM rollerinin atandığından emin olun.
Müşteri geliştirme ortamınızı kurun
Tüm ön koşulları karşıladığınızdan emin olun, ardından gerekli bağımlılıkları ve istemci kitaplıklarını uygulamanıza ekleyin.
iOS
- Firebase'i iOS uygulamanıza eklemek için talimatları izleyin.
- Cloud Functions bölmesini Pod dosyanıza
Podfile
:pod 'Firebase/Functions'
- Dosyayı kaydedin ve çalıştırın:
pod install
ağ
- Firebase'i Web uygulamanıza eklemek için talimatları izleyin.
- Firebase çekirdek ve Cloud Functions istemci kitaplıklarını uygulamanıza ekleyin:
<script src="https://www.gstatic.com/firebasejs/8.2.10/firebase.js"></script> <script src="https://www.gstatic.com/firebasejs/8.2.10/firebase-functions.js"></script>
Cloud Functions SDK, bir npm paketi olarak da mevcuttur.
- Aşağıdaki komutu terminalinizden çalıştırın:
npm install firebase@8.2.10 --save
- Hem Firebase çekirdeğini hem de Cloud Functions'ı manuel olarak gerekli kılın:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Java
Android uygulamanıza Firebase eklemek için talimatları izleyin.
Firebase Android BoM'yi kullanarak, modülünüzde (uygulama düzeyinde) Gradle dosyanızda (genellikle
app/build.gradle
) Cloud Functions Android kitaplığının bağımlılığınıapp/build.gradle
.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.6.0') // Declare 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'yi kullandığınızda , uygulamanız her zaman Firebase Android kitaplıklarının uyumlu sürümlerini kullanır.
(Alternatif) Bom kullanmadan Firebase kütüphane bağımlılıklarını beyan
Firebase BoM'yi kullanmamayı seçerseniz, bağımlılık satırında her bir Firebase kitaplık sürümünü belirtmeniz gerekir.
Uygulamanızda birden çok Firebase kitaplığı kullanırsanız, kitaplık sürümlerini yönetmek için BoM'yi kullanmanızı önemle tavsiye ettiğimizi unutmayın; bu, tüm sürümlerin uyumlu olmasını sağlar.
dependencies { // Declare 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:19.2.0' }
Kotlin + KTX
Android uygulamanıza Firebase eklemek için talimatları izleyin.
Firebase Android BoM'yi kullanarak, modülünüzde (uygulama düzeyinde) Gradle dosyanızda (genellikle
app/build.gradle
) Cloud Functions Android kitaplığının bağımlılığınıapp/build.gradle
.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.6.0') // Declare 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'yi kullandığınızda , uygulamanız her zaman Firebase Android kitaplıklarının uyumlu sürümlerini kullanır.
(Alternatif) Bom kullanmadan Firebase kütüphane bağımlılıklarını beyan
Firebase BoM'yi kullanmamayı seçerseniz, bağımlılık satırında her bir Firebase kitaplık sürümünü belirtmeniz gerekir.
Uygulamanızda birden çok Firebase kitaplığı kullanırsanız, kitaplık sürümlerini yönetmek için BoM'yi kullanmanızı önemle tavsiye ettiğimizi unutmayın;
dependencies { // Declare 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:19.2.0' }
C ++
Android ile C ++ için :
- Firebase'i C ++ projenize eklemek için talimatları uygulayın.
-
firebase_functions
kitaplığınıCMakeLists.txt
dosyanıza ekleyin.
İOS ile C ++ için :
- Firebase'i C ++ projenize eklemek için talimatları uygulayın.
- Cloud Functions bölmesini Pod dosyanıza
Podfile
:pod 'Firebase/Functions'
- Dosyayı kaydedin ve çalıştırın:
pod install
- Firebase C ++ SDK'sından Firebase core ve Cloud Functions çerçevelerini Xcode projenize ekleyin.
-
firebase.framework
-
firebase_functions.framework
-
Birlik
- Unity projenize Firebase eklemek için talimatları izleyin.
- Ekle
FirebaseFunctions.unitypackage
gelen Firebase Birlik SDK sizin Birlik projesine.
İstemci SDK'sını başlatın
Bir Cloud Functions örneğini başlatın:
Swift
lazy var functions = Functions.functions()
Amaç-C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
ağ
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();
Java
private FirebaseFunctions mFunctions; // ... mFunctions = FirebaseFunctions.getInstance();
Kotlin + KTX
private lateinit var functions: FirebaseFunctions // ... functions = Firebase.functions
C ++
firebase::functions::Functions* functions;
// ...
functions = firebase::functions::Functions::GetInstance(app);
Birlik
functions = Firebase.Functions.DefaultInstance;
İşlevi çağırın
Swift
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 text = result?.data as? String {
self.resultField.text = text
}
}
Amaç-C
[[_functions HTTPSCallableWithName:@"addMessage"] callWithObject:@{@"text": _inputField.text}
completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
if (error) {
if (error.domain == FIRFunctionsErrorDomain) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[FIRFunctionsErrorDetailsKey];
}
// ...
}
self->_resultField.text = result.data;
}];
ağ
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
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; } }); }
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 } }
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);
}
Birlik
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;
});
}
İstemcideki hataları işleyin
Sunucu bir hata verirse veya ortaya çıkan söz reddedilirse istemci bir hata alır.
İşlevi tarafından döndürülen hata tipi ise function.https.HttpsError
ardından istemci hatası aldığında code
, message
ve details
sunucu hatadan. Aksi takdirde, hata INTERNAL
mesajını ve INTERNAL
kodunu içerir. Çağrılabilir işlevinizdeki hataları nasıl ele alacağınızla ilgili kılavuza bakın.
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]
}
// ...
}
Amaç-C
if (error) {
if (error.domain == FIRFunctionsErrorDomain) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[FIRFunctionsErrorDetailsKey];
}
// ...
}
ağ
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;
// ...
});
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(); } // ... } // ... } });
Kotlin + KTX
addMessage(inputMessage) .addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { val code = e.code val details = e.details } // ... } // ... })
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);
// ...
Birlik
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;
}
});