Skip to main content
このページは AI コーディングエージェントスキルの一部で、人間ではなくエージェント向けに書かれています。人間向けの Base44 ドキュメントは デベロッパードキュメント を参照してください。

Functions モジュール

base44.functions を介したカスタムバックエンド関数の呼び出し。

目次

メソッド

invoke

base44.functions.invoke(functionName, data?): Promise<AxiosResponse>
  • functionName: バックエンド関数の名前
  • data: パラメーターのオプションオブジェクト (JSON として送信、または File オブジェクトを含む場合は multipart)
  • 生の axios レスポンスを返します — 関数が返した JSON は .data にあり、トップレベルのオブジェクトにはありません。解決される値は { data, status, headers, … } です。
  • 非 2xx レスポンスでスローします。 エラーボディは 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>
バックエンド関数パスへの直接的な HTTP リクエストを実行し、ネイティブの Response オブジェクトを返す低レベルメソッド。ストリーミングレスポンス、カスタム HTTP メソッド、または生のレスポンスアクセスが必要な場合に使用します。
  • path: 関数パス (例: /streaming_demo または /my-function/endpoint)
  • init: オプションのネイティブ fetch オプション (RequestInit)
  • 戻り値: ネイティブの Response オブジェクト

関数の呼び出し

フロントエンドから

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

ストリーミングレスポンス (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));
}

カスタム HTTP メソッド (fetch を使用)

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

ファイルアップロード付き

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

サービスロールで (バックエンド)

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

REST API 経由 (curl)

関数はアプリドメインへの HTTP POST 経由で呼び出せます:
curl -X POST "https://<app-domain>/functions/<function-name>" \
  -H "Content-Type: application/json" \
  -d '{"key": "value"}'

バックエンド関数の作成

バックエンド関数は Deno 上で実行されます。Deno.serve() を使ってエクスポートする必要があります。

関数ディレクトリ構造

バックエンド関数は base44/functions/ の下にある entry.ts または entry.js ファイルを含むフォルダーです:
base44/
  functions/
    process-order/
      entry.ts
関数名は base44/functions/ から entry.ts を含むフォルダーまでのパスです。たとえば、base44/functions/process-order/entry.tsprocess-order としてデプロイされ、base44/functions/orders/process/entry.tsorders/process としてデプロイされます。 完全なセットアップとデプロイの手順については、base44-cli の functions-create.md を参照してください。

基本構造

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

サービスロールアクセス付き

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

シークレットの使用

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

エラー処理

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

セットアップ要件

  1. アプリ設定でバックエンド関数を有効化 (適切なプランが必要)
  2. base44/functions/ に関数ファイルを作成
  3. API キー用にアプリダッシュボードでシークレットを構成

認証モード

モードコンテキスト権限
ユーザーbase44.functions.invoke()呼び出し元ユーザーの権限で実行
サービスロールbase44.asServiceRole.functions.invoke()管理者レベルアクセス
関数内では、呼び出し元の認証コンテキストを継承するクライアントを取得するために createClientFromRequest(req) を使用します。

型定義

型付き関数名の取得方法: Base44 CLI はプロジェクトから FunctionNameRegistry の拡張を生成できます。実行方法については、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>;
}
このページは AI を使用して翻訳されました。最も正確で最新の情報については、英語版 を参照してください。