Catch up on highlights from Firebase at Google I/O 2023. Learn more

Uygulamanızdan arama işlevleri


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şlev çağırmak için Cloud Functions'ta bir HTTP Callable işlevi yazıp dağıtın ve ardından, işlevi uygulamanızdan çağırmak için istemci mantığı ekleyin.

HTTP çağrılabilir işlevlerinin benzer olduğunu ancak HTTP işlevleriyle aynı olmadığını akılda tutmak önemlidir. HTTP çağrılabilir işlevlerini kullanmak için, arka uç API ile birlikte platformunuz için istemci SDK'sını kullanmanız (veya protokolü uygulamanız) gerekir. Callables, HTTP işlevlerinden şu temel farklara sahiptir:

Çağrılabilir öğeler, HTTP işlevlerinden şu temel farklılıklara sahiptir:

  • Çağrılabilir öğelerle, Firebase Kimlik Doğrulama belirteçleri, FCM belirteçleri ve varsa Uygulama Kontrolü belirteçleri isteklere otomatik olarak dahil edilir.
  • Tetikleyici, istek gövdesini otomatik olarak seri durumdan çıkarır ve kimlik doğrulama belirteçlerini doğrular.

Cloud Functions 2. nesil ve üstü için Firebase SDK, HTTPS Çağrılabilir işlevlerini desteklemek için bu Firebase istemci SDK'sı minimum sürümleriyle birlikte çalışır:

  • Apple platformları için Firebase SDK'sı 10.10.0
  • Android 20.3.1 için Firebase SDK'sı
  • Firebase Modüler Web SDK v. 9.7.0

Desteklenmeyen bir platformda oluşturulmuş bir uygulamaya benzer işlevler eklemek istiyorsanız, https.onCall için Protokol Spesifikasyonuna bakın. Bu kılavuzun geri kalanında, Apple platformları, Android, web, C++ ve Unity için çağrılabilir bir HTTP işlevinin nasıl yazılacağı, dağıtılacağı ve çağrılacağı ile ilgili yönergeler sağlanmaktadır.

Çağrılabilir işlevi yazın ve dağıtı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, bir metin mesajını Gerçek Zamanlı Veritabanına 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 oluşturabilir. Performansı optimize etmek için, uygun olduğunda işlev konumunu belirtmeyi düşünün ve istemci tarafında SDK'yı başlattığınızda çağrılabilir konumu ayarlanan konumla hizaladığınızdan emin olun.

İsteğe bağlı olarak, arka uç kaynaklarınızı fatura sahtekarlığı veya kimlik avı gibi kötüye kullanıma karşı korumaya yardımcı olması için bir Uygulama Kontrolü onayı ekleyebilirsiniz. Bkz . Bulut İşlevleri için Uygulama Kontrolü zorlamasını etkinleştirin .

Sonucu geri gönderme

Verileri istemciye geri göndermek için JSON kodlu olabilen 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,
};

Zaman uyumsuz bir işlemden sonra verileri döndürmek için bir söz ver. Taahhüt tarafından döndürülen veriler müşteriye geri gönderilir. Örneğin, çağrılabilir işlevin Realtime Database'e 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 };
})

İşleme hataları

İstemcinin faydalı hata ayrıntılarını almasını sağlamak için, bir functions.https.HttpsError örneğini atarak (veya reddedilen bir Sözü döndürerek) çağrılabilir bir hatadan döndürün. Hata, functions.https.HttpsError adresinde listelenen değerlerden biri olabilen bir code özniteliğine sahiptir. Hatalarda ayrıca varsayılan olarak boş bir dize olan bir message dizisi bulunur. İsteğe bağlı bir değere sahip isteğe bağlı bir details alanına da sahip olabilirler. İşlevlerinizden HttpsError dışında bir hata atılırsa, istemciniz bunun yerine INTERNAL mesajı ve internal koduyla bir hata alır.

Örneğin, bir işlev, çağıran istemciye geri dönmek için hata mesajları içeren 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 dağıtın

index.js içinde tamamlanmış çağrılabilir bir işlevi kaydettikten sonra, firebase deploy çalıştırdığınızda diğer tüm işlevlerle birlikte dağıtılır. Yalnızca çağrılabilir olanı konuşlandırmak için, --only bağımsız değişkenini gösterildiği gibi kullanarak kısmi konuşlandırmaları 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.

İstemci 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 Apple uygulamanıza eklemek için talimatları izleyin.

Firebase bağımlılıklarını kurmak ve yönetmek için Swift Paket Yöneticisi'ni kullanın.

  1. Xcode'da, uygulama projeniz açıkken File > Add Packages seçeneğine gidin.
  2. İstendiğinde, Firebase Apple platformları SDK deposunu ekleyin:
  3.   https://github.com/firebase/firebase-ios-sdk
  4. Cloud Functions kitaplığını seçin.
  5. Bittiğinde, Xcode otomatik olarak arka planda bağımlılıklarınızı çözmeye ve indirmeye başlayacaktır.

Web modüler API

  1. Firebase'i Web uygulamanıza eklemek için talimatları izleyin. Terminalinizden şu komutu çalıştırdığınızdan emin olun:
    npm install firebase@9.22.1 --save
    
  2. Hem Firebase çekirdeğini hem de Bulut İşlevlerini manuel olarak gerektir:

     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 ad alanlı API

  1. Firebase'i Web uygulamanıza eklemek için talimatları izleyin.
  2. Firebase çekirdeğini ve Cloud Functions istemci kitaplıklarını uygulamanıza ekleyin:
    <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, bir npm paketi olarak da mevcuttur.

  1. Terminalinizden şu komutu çalıştırın:
    npm install firebase@8.10.1 --save
    
  2. Hem Firebase çekirdeğini hem de Bulut İşlevlerini manuel olarak gerektir:
    const firebase = require("firebase");
    // Required for side-effects
    require("firebase/functions");
    

Kotlin+KTX

  1. Firebase'i Android uygulamanıza eklemek için talimatları uygulayın.

  2. Modül (uygulama düzeyinde) Gradle dosyanızda (genellikle <project>/<app-module>/build.gradle ), Cloud Functions Android kitaplığı için bağımlılığı ekleyin. Kitaplık sürüm oluşturmayı kontrol etmek için Firebase Android BoM'yi kullanmanızı öneririz.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.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'yi kullandığınızda, uygulamanız her zaman Firebase Android kitaplıklarının uyumlu sürümlerini kullanır.

    (Alternatif) BoM kullanmadan Firebase kitaplığı bağımlılıkları ekleyin

    Firebase BoM'yi kullanmamayı seçerseniz, her bir Firebase kitaplığı sürümünü bağımlılık satırında belirtmeniz gerekir.

    Uygulamanızda birden fazla Firebase kitaplığı kullanıyorsanız kitaplık sürümlerini yönetmek için tüm sürümlerin uyumlu olmasını sağlayan BoM'yi kullanmanızı kesinlikle öneririz.

    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.1'
    }
    

Java

  1. Firebase'i Android uygulamanıza eklemek için talimatları uygulayın.

  2. Modül (uygulama düzeyinde) Gradle dosyanızda (genellikle <project>/<app-module>/build.gradle ), Cloud Functions Android kitaplığı için bağımlılığı ekleyin. Kitaplık sürüm oluşturmayı kontrol etmek için Firebase Android BoM'yi kullanmanızı öneririz.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.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'yi kullandığınızda, uygulamanız her zaman Firebase Android kitaplıklarının uyumlu sürümlerini kullanır.

    (Alternatif) BoM kullanmadan Firebase kitaplığı bağımlılıkları ekleyin

    Firebase BoM'yi kullanmamayı seçerseniz, her bir Firebase kitaplığı sürümünü bağımlılık satırında belirtmeniz gerekir.

    Uygulamanızda birden fazla Firebase kitaplığı kullanıyorsanız kitaplık sürümlerini yönetmek için tüm sürümlerin uyumlu olmasını sağlayan BoM'yi kullanmanızı kesinlikle öneririz.

    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.1'
    }
    

Dart

  1. Firebase'i Flutter uygulamanıza eklemek için talimatları izleyin.

  2. Eklentiyi yüklemek için Flutter projenizin kökünden aşağıdaki komutu çalıştırın:

    flutter pub add cloud_functions
    
  3. Tamamlandığında, Flutter uygulamanızı yeniden oluşturun:

    flutter run
    
  4. Kurulduktan sonra, cloud_functions eklentisine Dart kodunuza aktararak erişebilirsiniz:

    import 'package:cloud_functions/cloud_functions.dart';
    

C++

Android ile C++ için:

  1. Firebase'i C++ projenize eklemek için talimatları izleyin.
  2. firebase_functions kitaplığını CMakeLists.txt dosyanıza ekleyin.

Apple platformları ile C++ için:

  1. Firebase'i C++ projenize eklemek için talimatları izleyin.
  2. Bulut İşlevleri bölmesini Pod Podfile ekleyin:
    pod 'Firebase/Functions'
  3. Dosyayı kaydedin ve şunu çalıştırın:
    pod install
  4. Firebase C++ SDK'daki Firebase çekirdeğini ve Cloud Functions çerçevelerini Xcode projenize ekleyin.
    • firebase.framework
    • firebase_functions.framework

Birlik

  1. Firebase'i Unity projenize eklemek için talimatları izleyin.
  2. Firebase Unity SDK'sındaki FirebaseFunctions.unitypackage Unity projenize ekleyin.

İstemci SDK'sını başlat

Cloud Functions'ın bir örneğini başlatın:

Süratli

lazy var functions = Functions.functions()

Amaç-C

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

Web ad alanlı API

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 modüler API

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);

Birlik

functions = Firebase.Functions.DefaultInstance;

işlevi çağır

Süratli

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
  }
}

Amaç-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 ad alanlı API

var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
  .then((result) => {
    // Read result of the Cloud Function.
    var sanitizedMessage = result.data.text;
  });

Web modüler API

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(
      {
        "text": text,
        "push": true,
      },
    );
    _response = result.data as String;

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şleme

İstemci, sunucu bir hata atarsa ​​veya sonuç taahhüdü reddedilirse bir hata alır.

İşlev tarafından döndürülen hata function.https.HttpsError türündeyse, istemci sunucu hatasından hata code , message ve details alır. Aksi takdirde hata, INTERNAL mesajını ve INTERNAL kodunu içerir. Çağrılabilir işlevinizdeki hataların nasıl ele alınacağına ilişkin kılavuza bakın.

Süratli

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 isEqual:@"com.firebase.functions"]) {
    FIRFunctionsErrorCode code = error.code;
    NSString *message = error.localizedDescription;
    NSObject *details = error.userInfo[@"details"];
  }
  // ...
}

Web ad alanlı API

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 modüler API

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);
  // ...

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;
  }
});

Uygulamanızı başlatmadan önce, çağrılabilir işlev uç noktalarınıza yalnızca uygulamalarınızın erişebildiğinden emin olmak için Uygulama Kontrolü'nü etkinleştirmelisiniz.