Chamar funções do seu aplicativo


Os SDKs de cliente do Cloud Functions para Firebase permitem chamar funções diretamente de um app do Firebase. Para chamar uma função do seu aplicativo dessa forma, escreva e implante uma função HTTP que pode ser chamada no Cloud Functions e, em seguida, adicione a lógica do cliente para chamar a função do seu aplicativo.

É importante ter em mente que as funções HTTP que podem ser chamadas são semelhantes, mas não idênticas, às funções HTTP. Para usar funções HTTP que podem ser chamadas, você deve usar o SDK do cliente para sua plataforma junto com a API de back-end (ou implementar o protocolo). Os callables têm estas principais diferenças em relação às funções HTTP:

  • Com os callables, os tokens do Firebase Authentication, os tokens FCM e os tokens do App Check, quando disponíveis, são automaticamente incluídos nas solicitações.
  • O gatilho desserializa automaticamente o corpo da solicitação e valida os tokens de autenticação.

O SDK do Firebase para Cloud Functions de segunda geração e versões superiores interopera com estas versões mínimas do SDK do cliente do Firebase para oferecer suporte a funções que podem ser chamadas por HTTPS:

  • SDK do Firebase para plataformas Apple 10.19.0
  • SDK do Firebase para Android 20.4.0
  • SDK Web Modular do Firebase v.

Se você quiser adicionar funcionalidade semelhante a um aplicativo criado em uma plataforma sem suporte, consulte a Especificação de protocolo para https.onCall . O restante deste guia fornece instruções sobre como escrever, implantar e chamar uma função HTTP chamável para plataformas Apple, Android, Web, C++ e Unity.

Escreva e implante a função que pode ser chamada

Os exemplos de código nesta seção baseiam-se em um exemplo de início rápido completo que demonstra como enviar solicitações para uma função do lado do servidor e obter uma resposta usando um dos SDKs do cliente. Para começar, importe os módulos necessários:

Node.js

// Dependencies for callable functions.
const {onCall, HttpsError} = require("firebase-functions/v2/https");
const {logger} = require("firebase-functions/v2");

// Dependencies for the addMessage function.
const {getDatabase} = require("firebase-admin/database");
const sanitizer = require("./sanitizer");

Pitão

# Dependencies for callable functions.
from firebase_functions import https_fn, options

# Dependencies for writing to Realtime Database.
from firebase_admin import db, initialize_app

Use o manipulador de solicitações da sua plataforma ( functions.https.onCall ) ou on_call ) para criar uma função HTTPS que pode ser chamada. Este método usa um parâmetro de solicitação:

Node.js

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

Pitão

@https_fn.on_call()
def addmessage(req: https_fn.CallableRequest) -> Any:
    """Saves a message to the Firebase Realtime Database but sanitizes the text
    by removing swear words."""

O parâmetro request contém dados transmitidos do aplicativo cliente, bem como contexto adicional, como estado de autenticação. Para uma função que pode ser chamada que salva uma mensagem de texto no Realtime Database, por exemplo, data podem conter o texto da mensagem, juntamente com informações de autenticação em auth :

Node.js

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

Pitão

# Message text passed from the client.
text = req.data["text"]
# Authentication / user information is automatically added to the request.
uid = req.auth.uid
name = req.auth.token.get("name", "")
picture = req.auth.token.get("picture", "")
email = req.auth.token.get("email", "")

A distância entre o local da função que pode ser chamada e o local do cliente chamador pode criar latência de rede. Para otimizar o desempenho, considere especificar o local da função quando aplicável e certifique-se de alinhar o local do chamável com o local definido ao inicializar o SDK no lado do cliente.

Opcionalmente, você pode anexar um atestado do App Check para ajudar a proteger seus recursos de back-end contra abusos, como fraude de faturamento ou phishing. Consulte Ativar a aplicação do App Check para Cloud Functions .

Enviando de volta o resultado

Para enviar dados de volta ao cliente, retorne dados que podem ser codificados em JSON. Por exemplo, para retornar o resultado de uma operação de adição:

Node.js

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

Pitão

return {
    "firstNumber": first_number,
    "secondNumber": second_number,
    "operator": "+",
    "operationResult": first_number + second_number
}

O texto limpo do exemplo de texto da mensagem é retornado ao cliente e ao Realtime Database. No Node.js, isso pode ser feito de forma assíncrona usando uma promessa JavaScript:

Node.js

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

Pitão

# Saving the new message to the Realtime Database.
sanitized_message = sanitize_text(text)  # Sanitize message.
db.reference("/messages").push({  # type: ignore
    "text": sanitized_message,
    "author": {
        "uid": uid,
        "name": name,
        "picture": picture,
        "email": email
    }
})
print("New message written")

# Returning the sanitized message to the client.
return {"text": sanitized_message}

Configurar CORS (compartilhamento de recursos entre origens)

Use a opção cors para controlar quais origens podem acessar sua função.

Por padrão, as funções que podem ser chamadas têm o CORS configurado para permitir solicitações de todas as origens. Para permitir algumas solicitações de origem cruzada, mas não todas, passe uma lista de domínios específicos ou expressões regulares que devem ser permitidas. Por exemplo:

Node.js

const { onCall } = require("firebase-functions/v2/https");

exports.getGreeting = onCall(
  { cors: [/firebase\.com$/, "flutter.com"] },
  (request) => {
    return "Hello, world!";
  }
);

Para proibir solicitações de origem cruzada, defina a política cors como false .

Lidar com erros

Para garantir que o cliente obtenha detalhes úteis do erro, retorne erros de um callable lançando (ou para Node.js retornando uma Promise rejeitada com) uma instância de functions.https.HttpsError ou https_fn.HttpsError . O erro possui um atributo code que pode ser um dos valores listados em códigos de status gRPC. Os erros também possuem uma string message , cujo padrão é uma string vazia. Eles também podem ter um campo details opcional com um valor arbitrário. Se um erro diferente de HTTPS for gerado em suas funções, seu cliente receberá um erro com a mensagem INTERNAL e o código internal .

Por exemplo, uma função pode lançar erros de validação e autenticação de dados com mensagens de erro para retornar ao cliente chamador:

Node.js

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

Pitão

# Checking attribute.
if not isinstance(text, str) or len(text) < 1:
    # Throwing an HttpsError so that the client gets the error details.
    raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.INVALID_ARGUMENT,
                              message=('The function must be called with one argument, "text",'
                                       " containing the message text to add."))

# Checking that the user is authenticated.
if req.auth is None:
    # Throwing an HttpsError so that the client gets the error details.
    raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.FAILED_PRECONDITION,
                              message="The function must be called while authenticated.")

Implantar a função que pode ser chamada

Depois de salvar uma função chamável concluída em index.js , ela será implantada junto com todas as outras funções quando você executar firebase deploy . Para implantar apenas o que pode ser chamado, use o argumento --only conforme mostrado para realizar implantações parciais :

firebase deploy --only functions:addMessage

Se você encontrar erros de permissão ao implantar funções, certifique-se de que as funções apropriadas do IAM estejam atribuídas ao usuário que executa os comandos de implantação.

Configure seu ambiente de desenvolvimento de cliente

Certifique-se de atender a todos os pré-requisitos e, em seguida, adicione as dependências e bibliotecas de cliente necessárias ao seu aplicativo.

iOS+

Siga as instruções para adicionar o Firebase ao seu aplicativo Apple .

Use o Swift Package Manager para instalar e gerenciar dependências do Firebase.

  1. No Xcode, com o projeto do seu aplicativo aberto, navegue até File > Add Packages .
  2. Quando solicitado, adicione o repositório SDK das plataformas Apple do Firebase:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Escolha a biblioteca do Cloud Functions.
  5. Adicione o sinalizador -ObjC à seção Outros sinalizadores de vinculador das configurações de compilação do seu destino.
  6. Quando terminar, o Xcode começará automaticamente a resolver e baixar suas dependências em segundo plano.

API modular da Web

  1. Siga as instruções para adicionar o Firebase ao seu aplicativo Web . Certifique-se de executar o seguinte comando em seu terminal:
    npm install firebase@10.7.1 --save
    
  2. Exija manualmente o núcleo do Firebase e o 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);
    

Android

  1. Siga as instruções para adicionar o Firebase ao seu aplicativo Android .

  2. No arquivo Gradle do módulo (nível do aplicativo) (geralmente <project>/<app-module>/build.gradle.kts ou <project>/<app-module>/build.gradle ), adicione a dependência para o Cloud Functions biblioteca para Android. Recomendamos usar o Firebase Android BoM para controlar o controle de versão da biblioteca.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.7.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")
    }
    

    Ao usar o Firebase Android BoM , seu aplicativo sempre usará versões compatíveis das bibliotecas do Firebase Android.

    (Alternativa) Adicionar dependências da biblioteca Firebase sem usar o BoM

    Se você optar por não usar o Firebase BoM, deverá especificar cada versão da biblioteca do Firebase em sua linha de dependência.

    Observe que se você usa várias bibliotecas do Firebase no seu aplicativo, é altamente recomendável usar a BoM para gerenciar as versões da biblioteca, o que garante que todas as versões sejam compatíveis.

    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.4.0")
    }
    
    Procurando um módulo de biblioteca específico para Kotlin? A partir de outubro de 2023 (Firebase BoM 32.5.0) , tanto os desenvolvedores Kotlin quanto os Java podem depender do módulo da biblioteca principal (para obter detalhes, consulte o FAQ sobre esta iniciativa ).

Inicialize o SDK do cliente

Inicialize uma instância do Cloud Functions:

Rápido

lazy var functions = Functions.functions()

Objetivo-C

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

API modular da Web

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

Chame a função

Rápido

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

Objetivo-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"];
}];

API com namespace da Web

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

API modular da Web

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

Unidade

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

Lidar com erros no cliente

O cliente recebe um erro se o servidor gerar um erro ou se a promessa resultante for rejeitada.

Se o erro retornado pela função for do tipo function.https.HttpsError , o cliente receberá o code de erro, message e details do erro do servidor. Caso contrário, o erro contém a mensagem INTERNAL e o código INTERNAL . Consulte orientações sobre como lidar com erros em sua função que pode ser chamada.

Rápido

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]
  }
  // ...
}

Objetivo-C

if (error) {
  if ([error.domain isEqual:@"com.firebase.functions"]) {
    FIRFunctionsErrorCode code = error.code;
    NSString *message = error.localizedDescription;
    NSObject *details = error.userInfo[@"details"];
  }
  // ...
}

API com namespace da Web

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

API modular da Web

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

Unidade

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

Antes de iniciar seu aplicativo, você deve ativar o App Check para ajudar a garantir que somente seus aplicativos possam acessar seus endpoints de função que podem ser chamados.

,


Os SDKs de cliente do Cloud Functions para Firebase permitem chamar funções diretamente de um app do Firebase. Para chamar uma função do seu aplicativo dessa maneira, escreva e implante uma função HTTP que pode ser chamada no Cloud Functions e, em seguida, adicione a lógica do cliente para chamar a função do seu aplicativo.

É importante ter em mente que as funções HTTP que podem ser chamadas são semelhantes, mas não idênticas, às funções HTTP. Para usar funções HTTP que podem ser chamadas, você deve usar o SDK do cliente para sua plataforma junto com a API de back-end (ou implementar o protocolo). Os callables têm estas principais diferenças em relação às funções HTTP:

  • Com os callables, os tokens do Firebase Authentication, os tokens FCM e os tokens do App Check, quando disponíveis, são automaticamente incluídos nas solicitações.
  • O gatilho desserializa automaticamente o corpo da solicitação e valida os tokens de autenticação.

O SDK do Firebase para Cloud Functions de segunda geração e versões superiores interopera com estas versões mínimas do SDK do cliente do Firebase para oferecer suporte a funções que podem ser chamadas por HTTPS:

  • SDK do Firebase para plataformas Apple 10.19.0
  • SDK do Firebase para Android 20.4.0
  • SDK Web Modular do Firebase v.

Se você quiser adicionar funcionalidade semelhante a um aplicativo criado em uma plataforma sem suporte, consulte a Especificação de protocolo para https.onCall . O restante deste guia fornece instruções sobre como escrever, implantar e chamar uma função HTTP chamável para plataformas Apple, Android, Web, C++ e Unity.

Escreva e implante a função que pode ser chamada

Os exemplos de código nesta seção baseiam-se em um exemplo de início rápido completo que demonstra como enviar solicitações para uma função do lado do servidor e obter uma resposta usando um dos SDKs do cliente. Para começar, importe os módulos necessários:

Node.js

// Dependencies for callable functions.
const {onCall, HttpsError} = require("firebase-functions/v2/https");
const {logger} = require("firebase-functions/v2");

// Dependencies for the addMessage function.
const {getDatabase} = require("firebase-admin/database");
const sanitizer = require("./sanitizer");

Pitão

# Dependencies for callable functions.
from firebase_functions import https_fn, options

# Dependencies for writing to Realtime Database.
from firebase_admin import db, initialize_app

Use o manipulador de solicitações da sua plataforma ( functions.https.onCall ) ou on_call ) para criar uma função HTTPS que pode ser chamada. Este método usa um parâmetro de solicitação:

Node.js

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

Pitão

@https_fn.on_call()
def addmessage(req: https_fn.CallableRequest) -> Any:
    """Saves a message to the Firebase Realtime Database but sanitizes the text
    by removing swear words."""

O parâmetro request contém dados transmitidos do aplicativo cliente, bem como contexto adicional, como estado de autenticação. Para uma função que pode ser chamada que salva uma mensagem de texto no Realtime Database, por exemplo, data podem conter o texto da mensagem, juntamente com informações de autenticação em auth :

Node.js

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

Pitão

# Message text passed from the client.
text = req.data["text"]
# Authentication / user information is automatically added to the request.
uid = req.auth.uid
name = req.auth.token.get("name", "")
picture = req.auth.token.get("picture", "")
email = req.auth.token.get("email", "")

A distância entre o local da função que pode ser chamada e o local do cliente chamador pode criar latência de rede. Para otimizar o desempenho, considere especificar o local da função quando aplicável e certifique-se de alinhar o local do chamável com o local definido ao inicializar o SDK no lado do cliente.

Opcionalmente, você pode anexar um atestado do App Check para ajudar a proteger seus recursos de back-end contra abusos, como fraude de faturamento ou phishing. Consulte Ativar a aplicação do App Check para Cloud Functions .

Enviando de volta o resultado

Para enviar dados de volta ao cliente, retorne dados que podem ser codificados em JSON. Por exemplo, para retornar o resultado de uma operação de adição:

Node.js

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

Pitão

return {
    "firstNumber": first_number,
    "secondNumber": second_number,
    "operator": "+",
    "operationResult": first_number + second_number
}

O texto limpo do exemplo de texto da mensagem é retornado ao cliente e ao Realtime Database. No Node.js, isso pode ser feito de forma assíncrona usando uma promessa JavaScript:

Node.js

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

Pitão

# Saving the new message to the Realtime Database.
sanitized_message = sanitize_text(text)  # Sanitize message.
db.reference("/messages").push({  # type: ignore
    "text": sanitized_message,
    "author": {
        "uid": uid,
        "name": name,
        "picture": picture,
        "email": email
    }
})
print("New message written")

# Returning the sanitized message to the client.
return {"text": sanitized_message}

Configurar CORS (compartilhamento de recursos entre origens)

Use a opção cors para controlar quais origens podem acessar sua função.

Por padrão, as funções que podem ser chamadas têm o CORS configurado para permitir solicitações de todas as origens. Para permitir algumas solicitações de origem cruzada, mas não todas, passe uma lista de domínios específicos ou expressões regulares que devem ser permitidas. Por exemplo:

Node.js

const { onCall } = require("firebase-functions/v2/https");

exports.getGreeting = onCall(
  { cors: [/firebase\.com$/, "flutter.com"] },
  (request) => {
    return "Hello, world!";
  }
);

Para proibir solicitações de origem cruzada, defina a política cors como false .

Lidar com erros

Para garantir que o cliente obtenha detalhes úteis do erro, retorne erros de um callable lançando (ou para Node.js retornando uma Promise rejeitada com) uma instância de functions.https.HttpsError ou https_fn.HttpsError . O erro possui um atributo code que pode ser um dos valores listados em códigos de status gRPC. Os erros também possuem uma string message , cujo padrão é uma string vazia. Eles também podem ter um campo details opcional com um valor arbitrário. Se um erro diferente de HTTPS for gerado em suas funções, seu cliente receberá um erro com a mensagem INTERNAL e o código internal .

Por exemplo, uma função pode lançar erros de validação e autenticação de dados com mensagens de erro para retornar ao cliente chamador:

Node.js

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

Pitão

# Checking attribute.
if not isinstance(text, str) or len(text) < 1:
    # Throwing an HttpsError so that the client gets the error details.
    raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.INVALID_ARGUMENT,
                              message=('The function must be called with one argument, "text",'
                                       " containing the message text to add."))

# Checking that the user is authenticated.
if req.auth is None:
    # Throwing an HttpsError so that the client gets the error details.
    raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.FAILED_PRECONDITION,
                              message="The function must be called while authenticated.")

Implantar a função que pode ser chamada

Depois de salvar uma função chamável concluída em index.js , ela será implantada junto com todas as outras funções quando você executar firebase deploy . Para implantar apenas o que pode ser chamado, use o argumento --only conforme mostrado para realizar implantações parciais :

firebase deploy --only functions:addMessage

Se você encontrar erros de permissão ao implantar funções, certifique-se de que as funções apropriadas do IAM estejam atribuídas ao usuário que executa os comandos de implantação.

Configure seu ambiente de desenvolvimento de cliente

Certifique-se de atender a todos os pré-requisitos e, em seguida, adicione as dependências e bibliotecas de cliente necessárias ao seu aplicativo.

iOS+

Siga as instruções para adicionar o Firebase ao seu aplicativo Apple .

Use o Swift Package Manager para instalar e gerenciar dependências do Firebase.

  1. No Xcode, com o projeto do seu aplicativo aberto, navegue até File > Add Packages .
  2. Quando solicitado, adicione o repositório SDK das plataformas Apple do Firebase:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. Escolha a biblioteca do Cloud Functions.
  5. Adicione o sinalizador -ObjC à seção Outros sinalizadores de vinculador das configurações de compilação do seu destino.
  6. Quando terminar, o Xcode começará automaticamente a resolver e baixar suas dependências em segundo plano.

API modular da Web

  1. Siga as instruções para adicionar o Firebase ao seu aplicativo Web . Certifique-se de executar o seguinte comando em seu terminal:
    npm install firebase@10.7.1 --save
    
  2. Exija manualmente o núcleo do Firebase e o 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);
    

Android

  1. Siga as instruções para adicionar o Firebase ao seu aplicativo Android .

  2. No arquivo Gradle do módulo (nível do aplicativo) (geralmente <project>/<app-module>/build.gradle.kts ou <project>/<app-module>/build.gradle ), adicione a dependência para o Cloud Functions biblioteca para Android. Recomendamos usar o Firebase Android BoM para controlar o controle de versão da biblioteca.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.7.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")
    }
    

    Ao usar o Firebase Android BoM , seu aplicativo sempre usará versões compatíveis das bibliotecas do Firebase Android.

    (Alternativa) Adicionar dependências da biblioteca Firebase sem usar o BoM

    Se você optar por não usar o Firebase BoM, deverá especificar cada versão da biblioteca do Firebase em sua linha de dependência.

    Observe que se você usa várias bibliotecas do Firebase no seu aplicativo, é altamente recomendável usar a BoM para gerenciar as versões da biblioteca, o que garante que todas as versões sejam compatíveis.

    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.4.0")
    }
    
    Procurando um módulo de biblioteca específico para Kotlin? A partir de outubro de 2023 (Firebase BoM 32.5.0) , tanto os desenvolvedores Kotlin quanto os Java podem depender do módulo da biblioteca principal (para obter detalhes, consulte o FAQ sobre esta iniciativa ).

Inicialize o SDK do cliente

Inicialize uma instância do Cloud Functions:

Rápido

lazy var functions = Functions.functions()

Objetivo-C

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

API modular da Web

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

Chame a função

Rápido

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

Objetivo-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"];
}];

API com namespace da Web

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

API modular da Web

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

Unidade

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

Lidar com erros no cliente

O cliente recebe um erro se o servidor gerar um erro ou se a promessa resultante for rejeitada.

Se o erro retornado pela função for do tipo function.https.HttpsError , o cliente receberá o code de erro, message e details do erro do servidor. Caso contrário, o erro contém a mensagem INTERNAL e o código INTERNAL . Consulte orientações sobre como lidar com erros em sua função que pode ser chamada.

Rápido

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]
  }
  // ...
}

Objetivo-C

if (error) {
  if ([error.domain isEqual:@"com.firebase.functions"]) {
    FIRFunctionsErrorCode code = error.code;
    NSString *message = error.localizedDescription;
    NSObject *details = error.userInfo[@"details"];
  }
  // ...
}

API com namespace da Web

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

API modular da Web

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

Unidade

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

Antes de iniciar seu aplicativo, você deve ativar o App Check para ajudar a garantir que somente seus aplicativos possam acessar seus endpoints de função que podem ser chamados.