Skip to main content
Questa pagina fa parte di una skill per agenti IA di programmazione ed è scritta per gli agenti, non per gli umani. Per la documentazione Base44 leggibile dagli umani, consulta la documentazione per sviluppatori.

Modulo Functions

Invoca funzioni backend personalizzate tramite base44.functions.

Contenuti

Metodi

invoke

base44.functions.invoke(functionName, data?): Promise<AxiosResponse>
  • functionName: nome della funzione backend
  • data: oggetto opzionale di parametri (inviato come JSON o come multipart se contiene oggetti File)
  • Restituisce la risposta axios GREZZA — il JSON restituito dalla funzione si trova in .data, non nell’oggetto di primo livello. Il valore risolto è { data, status, headers, … }.
  • Genera un errore in caso di risposta non 2xx. Il corpo dell’errore si trova in err.response.data.
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

base44.functions.fetch(path, init?): Promise<Response>
Metodo di basso livello che esegue una richiesta HTTP diretta a un percorso di funzione backend e restituisce l’oggetto Response nativo. Usalo quando ti servono risposte in streaming, metodi HTTP personalizzati o accesso grezzo alla risposta.
  • path: percorso della funzione (ad esempio /streaming_demo o /my-function/endpoint)
  • init: opzioni fetch native opzionali (RequestInit)
  • Restituisce: oggetto Response nativo

Invocare le funzioni

Dal frontend

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

Risposta in streaming (usando fetch)

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

Metodi HTTP personalizzati (usando fetch)

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

Con upload di file

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

Con service role (backend)

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

Tramite API REST (curl)

Le funzioni possono essere chiamate tramite HTTP POST al dominio della tua app:
curl -X POST "https://<app-domain>/functions/<function-name>" \
  -H "Content-Type: application/json" \
  -d '{"key": "value"}'

Scrivere funzioni backend

Le funzioni backend vengono eseguite su Deno. Devono essere esportate usando Deno.serve().

Struttura della directory della funzione

Una funzione backend è una cartella sotto base44/functions/ con un file entry.ts o entry.js:
base44/
  functions/
    process-order/
      entry.ts
Il nome della funzione è il percorso da base44/functions/ alla cartella che contiene entry.ts. Ad esempio, base44/functions/process-order/entry.ts viene distribuito come process-order e base44/functions/orders/process/entry.ts viene distribuito come orders/process. Per istruzioni complete di configurazione e distribuzione, consulta functions-create.md in base44-cli.

Struttura base

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

Con accesso service role

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

Usare i segreti

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

Gestione degli errori

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

Requisiti di configurazione

  1. Abilita le funzioni backend nelle impostazioni dell’app (richiede un piano adatto)
  2. Crea i file delle funzioni in base44/functions/
  3. Configura i segreti tramite la dashboard dell’app per le chiavi API

Modalità di autenticazione

ModalitàContestoPermessi
Userbase44.functions.invoke()Viene eseguito con i permessi dell’utente chiamante
Service Rolebase44.asServiceRole.functions.invoke()Accesso a livello di amministratore
All’interno della funzione, usa createClientFromRequest(req) per ottenere un client che eredita il contesto di autenticazione del chiamante.

Definizioni dei tipi

Come ottenere nomi di funzione tipizzati: la CLI di Base44 può generare un’estensione di FunctionNameRegistry a partire dal tuo progetto. Per sapere come eseguirla, usa la skill base44-cli.
/**
 * 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>;
}
Questa pagina è stata tradotta utilizzando l’IA. Per informazioni più accurate e aggiornate, consulta la versione inglese.