> ## Documentation Index
> Fetch the complete documentation index at: https://docs.base44.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Módulo Functions

> Invoca funções de backend personalizadas via base44.functions.

<Warning>
  Esta página faz parte de uma habilidade de agente de código IA e é escrita para agentes, não para humanos. Para a documentação legível por humanos da Base44, veja a [documentação para desenvolvedores](/developers).
</Warning>

# Módulo Functions

Invoca funções de backend personalizadas via `base44.functions`.

## Conteúdo

* [Método](#method)
* [Invocando funções](#invoking-functions) (Frontend, Upload de arquivo, Service Role, API REST)
* [Escrevendo funções de backend](#writing-backend-functions) (Básico, Service Role, Segredos, Erros)
* [Requisitos de configuração](#setup-requirements)
* [Modos de autenticação](#authentication-modes)

## Métodos

### `invoke`

```javascript theme={null}
base44.functions.invoke(functionName, data?): Promise<AxiosResponse>
```

* `functionName`: Nome da função de backend
* `data`: Objeto opcional de parâmetros (enviado como JSON, ou multipart se contém objetos File)
* **Retorna a resposta axios BRUTA** — o JSON que sua função retornou fica em **`.data`**, não no objeto de nível superior. O valor resolvido é `{ data, status, headers, … }`.
* **Lança em resposta não-2xx.** O corpo do erro está em `err.response.data`.

```javascript theme={null}
try {
  // ⚠️ invoke() returns the RAW axios response, so the JSON your function
  //    returned lives on `.data` — NOT on the top-level object.
  const res = await base44.functions.invoke("process-order", { orderId });
  const result = res.data;        // ✅  e.g. res.data.success
  // const result = res;          // ❌  this is { data, status, headers, … }
} catch (err) {
  // invoke() THROWS on a non-2xx response; the error body is at err.response.data.
  console.error(err.response?.data);
}
```

### `fetch`

```javascript theme={null}
base44.functions.fetch(path, init?): Promise<Response>
```

Método de baixo nível que realiza uma solicitação HTTP direta a um caminho de função de backend e retorna o objeto `Response` nativo. Use quando precisar de respostas em streaming, métodos HTTP personalizados ou acesso à resposta bruta.

* `path`: Caminho da função (por exemplo, `/streaming_demo` ou `/my-function/endpoint`)
* `init`: Opções nativas de fetch opcionais (`RequestInit`)
* Retorna: Objeto `Response` nativo

## Invocando funções

### Do frontend

```javascript theme={null}
const res = await base44.functions.invoke("processOrder", {
  orderId: "order-123",
  action: "ship"
});

// invoke() resolves to the raw axios response — read your function's JSON off .data
const result = res.data;
console.log(result);
```

### Resposta em streaming (usando fetch)

```javascript theme={null}
// Use fetch() for streaming responses (SSE, chunked text, etc.)
const response = await base44.functions.fetch("/stream-data", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ prompt: "Tell me a story" })
});

// Read as a stream
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  console.log(decoder.decode(value));
}
```

### Métodos HTTP personalizados (usando fetch)

```javascript theme={null}
// PUT, PATCH, DELETE, or other methods
const response = await base44.functions.fetch("/my-resource/123", {
  method: "DELETE"
});
console.log(response.status); // 204
```

### Com upload de arquivo

```javascript theme={null}
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

// Automatically uses multipart/form-data when File objects present
const res = await base44.functions.invoke("uploadDocument", {
  file: file,
  category: "invoices"
});
const result = res.data; // function's JSON is on .data
```

### Com Service Role (Backend)

```javascript theme={null}
// Inside another backend function
const res = await base44.asServiceRole.functions.invoke("adminTask", {
  userId: "user-123"
});
const result = res.data; // function's JSON is on .data
```

### Via API REST (curl)

As funções podem ser chamadas via HTTP POST para o domínio do seu aplicativo:

```bash theme={null}
curl -X POST "https://<app-domain>/functions/<function-name>" \
  -H "Content-Type: application/json" \
  -d '{"key": "value"}'
```

## Escrevendo funções de backend

Funções de backend rodam no Deno. Devem exportar usando `Deno.serve()`.

### Estrutura de diretório de funções

Uma função de backend é uma pasta em `base44/functions/` com um arquivo `entry.ts` ou `entry.js`:

```
base44/
  functions/
    process-order/
      entry.ts
```

O nome da função é o caminho de `base44/functions/` até a pasta contendo `entry.ts`. Por exemplo, `base44/functions/process-order/entry.ts` implanta como `process-order`, e `base44/functions/orders/process/entry.ts` implanta como `orders/process`.

Para instruções completas de configuração e implantação, veja [functions-create.md](https://docs.base44.com/developers/skills/base44-sdk/references/../../base44-cli/references/functions-create.md) em base44-cli.

### Estrutura básica

```javascript theme={null}
// base44/functions/process-order/entry.ts
import { createClientFromRequest } from "npm:@base44/sdk";

Deno.serve(async (req) => {
  // Get authenticated client from request
  const base44 = createClientFromRequest(req);
  
  // Parse input
  const { orderId, action } = await req.json();
  
  // Your logic here
  const order = await base44.entities.Orders.get(orderId);
  
  // Return response
  return Response.json({
    success: true,
    order: order
  });
});
```

### Com acesso Service Role

```javascript theme={null}
import { createClientFromRequest } from "npm:@base44/sdk";

Deno.serve(async (req) => {
  const base44 = createClientFromRequest(req);
  
  // Check user is authenticated
  const user = await base44.auth.me();
  if (!user) {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }
  
  // Use service role for admin operations
  const allOrders = await base44.asServiceRole.entities.Orders.list();
  
  return Response.json({ orders: allOrders });
});
```

### Usando segredos

```javascript theme={null}
Deno.serve(async (req) => {
  // Access environment variables (configured in app settings)
  const apiKey = Deno.env.get("STRIPE_API_KEY");
  
  const response = await fetch("https://api.stripe.com/v1/charges", {
    headers: {
      "Authorization": `Bearer ${apiKey}`
    }
  });
  
  return Response.json(await response.json());
});
```

### Tratamento de erros

```javascript theme={null}
import { createClientFromRequest } from "npm:@base44/sdk";

Deno.serve(async (req) => {
  try {
    const base44 = createClientFromRequest(req);
    const { orderId } = await req.json();
    
    const order = await base44.entities.Orders.get(orderId);
    if (!order) {
      return Response.json(
        { error: "Order not found" },
        { status: 404 }
      );
    }
    
    return Response.json({ order });
    
  } catch (error) {
    return Response.json(
      { error: error.message },
      { status: 500 }
    );
  }
});
```

## Requisitos de configuração

1. Ative as funções de backend nas configurações do aplicativo (requer plano apropriado)
2. Crie arquivos de função em `base44/functions/`
3. Configure segredos pelo painel do aplicativo para chaves de API

## Modos de autenticação

| Modo         | Contexto                                  | Permissões                              |
| ------------ | ----------------------------------------- | --------------------------------------- |
| Usuário      | `base44.functions.invoke()`               | Roda com permissões do usuário chamador |
| Service Role | `base44.asServiceRole.functions.invoke()` | Acesso em nível de administrador        |

Dentro da função, use `createClientFromRequest(req)` para obter um cliente que herda o contexto de autenticação do chamador.

## Definições de tipo

**Como obter nomes de função tipados:** A CLI Base44 pode gerar um aumento de `FunctionNameRegistry` do seu projeto. Para saber como executá-la, use a habilidade **base44-cli**.

```typescript theme={null}
/**
 * Registry of function names.
 * Augment this interface to enable autocomplete for function names.
 * Typically populated by the Base44 CLI type generator.
 */
interface FunctionNameRegistry {}

/**
 * Function name type - uses registry keys if augmented, otherwise string.
 */
type FunctionName = keyof FunctionNameRegistry extends never ? string : keyof FunctionNameRegistry;

/**
 * Options for functions.fetch(). Uses native fetch options directly.
 */
type FunctionsFetchInit = RequestInit;

/** Functions module for invoking custom backend functions. */
interface FunctionsModule {
  /**
   * Invokes a custom backend function by name.
   *
   * If any parameter is a File object, the request will automatically be
   * sent as multipart/form-data. Otherwise, it will be sent as JSON.
   *
   * @param functionName - The name of the function to invoke.
   * @param data - Optional object containing named parameters for the function.
   * @returns Promise resolving to the function's response.
   */
  invoke(functionName: FunctionName, data?: Record<string, any>): Promise<any>;

  /**
   * Performs a direct HTTP request to a backend function path and returns the native Response.
   *
   * Use for streaming responses (SSE, chunked text), custom HTTP methods,
   * or when you need raw access to the response.
   *
   * @param path - Function path, e.g. `/streaming_demo` or `/my-function/endpoint`
   * @param init - Optional native fetch options.
   * @returns Promise resolving to a native fetch Response.
   */
  fetch(path: string, init?: FunctionsFetchInit): Promise<Response>;
}
```

<Note>Esta página foi traduzida usando IA. Para informações mais precisas e atualizadas, consulte a [versão em inglês](/). </Note>
