> ## 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.

# 関数の作成

> Base44 の関数は Deno 上で実行されるサーバーレスバックエンド関数です。プロジェクト内でローカルに定義され、Base44 バックエンドにデプロイされます。

<Warning>
  このページは AI コーディングエージェントスキルの一部で、人間ではなくエージェント向けに書かれています。人間向けの Base44 ドキュメントは [デベロッパードキュメント](/developers) を参照してください。
</Warning>

# 関数の作成

Base44 の関数は Deno 上で実行されるサーバーレスバックエンド関数です。プロジェクト内でローカルに定義され、Base44 バックエンドにデプロイされます。

## 関数ディレクトリ

すべての関数定義はプロジェクトの `base44/functions/` フォルダーに配置する必要があります。最もシンプルな関数は、`entry.ts` または `entry.js` ファイルを含むフォルダーです。

構造の例:

```
my-app/
  base44/
    functions/
      process-order/
        entry.ts
      send-notification/
        entry.ts
```

## 関数の作成方法

1. `base44/functions/` に関数名で新しいディレクトリを作成します (kebab-case を使用)
2. そのディレクトリに `entry.ts` (または `entry.js`) を作成します
3. CLI を使用して関数をデプロイします

## 関数の検出

CLI は `entry.ts` または `entry.js` ファイルから関数を検出します。それらのファイルのいずれかを含むフォルダーが関数です:

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

関数名は functions ルートからそのフォルダーまでのパスです。例:

| ファイル                                       | 関数名              |
| ------------------------------------------ | ---------------- |
| `base44/functions/process-order/entry.ts`  | `process-order`  |
| `base44/functions/orders/process/entry.ts` | `orders/process` |

ルール:

* `entry.ts` または `entry.js` は `base44/functions/` 直下ではなく、名前付きサブフォルダー内にある必要があります
* 関数フォルダー内のすべての `*.js`、`*.ts`、`*.json` ファイルはデプロイ時に含まれます
* パスセグメントにドットを含む関数パスは無視されます

## エントリーポイントファイル

関数は Deno 上で実行され、`Deno.serve()` を使用してエクスポートする必要があります。npm パッケージには `npm:` プレフィックスを使用します。

```typescript theme={null}
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
  });
});
```

### Request オブジェクト

関数は標準の Deno `Request` オブジェクトを受け取ります:

* `req.json()` - JSON ボディを解析
* `req.text()` - 生のテキストボディを取得
* `req.headers` - リクエストヘッダーにアクセス
* `req.method` - HTTP メソッド

### Response オブジェクト

JSON レスポンスには `Response.json()` を使用して返します:

```typescript theme={null}
// Success response
return Response.json({ data: result });

// Error response with status code
return Response.json({ error: "Something went wrong" }, { status: 400 });

// Not found
return Response.json({ error: "Order not found" }, { status: 404 });
```

## 完全な例

### ディレクトリ構造

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

### entry.ts

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

Deno.serve(async (req) => {
  try {
    const base44 = createClientFromRequest(req);
    const { orderId } = await req.json();
    
    // Validate input
    if (!orderId) {
      return Response.json(
        { error: "Order ID is required" },
        { status: 400 }
      );
    }
    
    // Fetch and process the order
    const order = await base44.entities.Orders.get(orderId);
    if (!order) {
      return Response.json(
        { error: "Order not found" },
        { status: 404 }
      );
    }
    
    return Response.json({
      success: true,
      orderId: order.id,
      processedAt: new Date().toISOString()
    });
    
  } catch (error) {
    return Response.json(
      { error: error.message },
      { status: 500 }
    );
  }
});
```

## サービスロールアクセスの使用

管理者レベルの操作には `asServiceRole` を使用します:

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

## シークレットの使用

アプリダッシュボードで設定された環境変数にアクセス:

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

## 命名規則

* **ディレクトリ名**: kebab-case を使用 (例: `process-order`, `send-notification`)
* **関数名**: `base44/functions/` の下のディレクトリパスから決まります
  * 有効: `process-order`, `orders/process`, `send_notification`, `myFunction`
  * 無効: `process.order`, `send.notification.v2`
* **エントリーファイル**: `entry.ts` または `entry.js` を使用

## 関数のデプロイ

関数を作成したら、Base44 にデプロイします:

```bash theme={null}
npx base44 functions deploy
```

デプロイの詳細は [functions-deploy.md](https://docs.base44.com/developers/skills/base44-cli/references/functions-deploy.md) を参照してください。

## 注意事項

* 関数は Node.js ではなく Deno ランタイム上で実行されます
* npm パッケージには `npm:` プレフィックスを使用します (例: `npm:@base44/sdk`)
* 呼び出し元の認証コンテキストを継承するクライアントを取得するには `createClientFromRequest(req)` を使用します
* API キーは app ダッシュボードでシークレットを設定します
* エラーを適切に処理し、適切な HTTP ステータスコードを返してください

## よくある間違い

| 誤                                         | 正                                       | 理由                                      |
| ----------------------------------------- | --------------------------------------- | --------------------------------------- |
| `base44/functions/myFunction.js` (単一ファイル) | `base44/functions/my-function/entry.ts` | 関数は名前付きサブディレクトリに存在する必要があります             |
| `base44/functions/entry.ts`               | `base44/functions/my-function/entry.ts` | 関数名はサブディレクトリパスから決まります                   |
| `import { ... } from "@base44/sdk"`       | `import { ... } from "npm:@base44/sdk"` | Deno は npm パッケージに `npm:` プレフィックスを必要とします |
| `MyFunction` または `myFunction` ディレクトリ      | `my-function` ディレクトリ                    | ディレクトリ名には kebab-case を使用します             |

<Note>このページは AI を使用して翻訳されました。最も正確で最新の情報については、[英語版](/) を参照してください。 </Note>
