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

# 函數 SDK 參考

> 使用 InsForge Swift SDK 叫用無伺服器函數

## 安裝

Add InsForge to your Swift Package Manager dependencies:

```swift theme={null}
dependencies: [
    .package(url: "https://github.com/insforge/insforge-swift.git", from: "0.0.9")
]
```

```swift theme={null}
import InsForge

let insforge = InsForgeClient(
    baseURL: URL(string: "https://your-app.insforge.app")!,
    anonKey: "your-anon-key"
)
```

### Enable Logging (Optional)

For debugging, you can configure the SDK log level and destination:

```swift theme={null}
let options = InsForgeClientOptions(
    global: .init(
        logLevel: .debug,
        logDestination: .osLog,
        logSubsystem: "com.example.MyApp"
    )
)

let insforge = InsForgeClient(
    baseURL: URL(string: "https://your-app.insforge.app")!,
    anonKey: "your-anon-key",
    options: options
)
```

**Log Levels:**

| Level       | Description                                 |
| ----------- | ------------------------------------------- |
| `.trace`    | Most verbose, includes all internal details |
| `.debug`    | Detailed information for debugging          |
| `.info`     | General operational information (default)   |
| `.warning`  | Warnings that don't prevent operation       |
| `.error`    | Errors that affect functionality            |
| `.critical` | Critical failures                           |

**Log Destinations:**

| Destination | Description                                                |
| ----------- | ---------------------------------------------------------- |
| `.console`  | Standard output (print)                                    |
| `.osLog`    | Apple's unified logging system (recommended for iOS/macOS) |
| `.none`     | Disable logging                                            |
| `.custom`   | Provide your own LogHandler factory                        |

<Note>
  Use `.info` or `.error` in production to avoid exposing sensitive data in logs.
</Note>

<Note>
  目前，InsForge 僅支援在 Deno 環境中執行的 JavaScript/TypeScript 函數。
</Note>

***

## invoke()

按 slug 叫用無伺服器函數。

### 參數

* `slug` (String) - 函數 slug/名稱
* `body` (\[String: Any], optional) - 要求主體作為字典

### 多載

`invoke` 方法有三個多載：

1. **使用字典主體，傳回類型化回應**
   ```swift theme={null}
   func invoke<T: Decodable>(_ slug: String, body: [String: Any]?) async throws -> T
   ```

2. **使用 Encodable 主體，傳回類型化回應**
   ```swift theme={null}
   func invoke<I: Encodable, O: Decodable>(_ slug: String, body: I) async throws -> O
   ```

3. **不期望回應主體**
   ```swift theme={null}
   func invoke(_ slug: String, body: [String: Any]?) async throws
   ```

<Note>
  SDK 會自動包含來自登入使用者的驗證令牌。
</Note>

***

## 範例

### 範例：基本叫用與類型化回應

```swift theme={null}
// Define response model
struct HelloResponse: Codable {
    let message: String
    let timestamp: String
}

// Invoke function with dictionary body
let response: HelloResponse = try await insforge.functions.invoke(
    "hello-world",
    body: ["name": "World", "greeting": "Hello"]
)

print(response.message)  // "Hello, World!"
```

### 範例：使用 Encodable 要求主體

```swift theme={null}
// Define request and response models
struct GreetingRequest: Codable {
    let name: String
    let greeting: String
}

struct GreetingResponse: Codable {
    let message: String
    let timestamp: String
}

// Invoke with typed request
let request = GreetingRequest(name: "World", greeting: "Hello")
let response: GreetingResponse = try await insforge.functions.invoke(
    "hello-world",
    body: request
)

print(response.message)
```

***

## 錯誤處理

```swift theme={null}
do {
    let response: MyResponse = try await insforge.functions.invoke(
        "my-function",
        body: ["key": "value"]
    )
    print("Success: \\(response)")
} catch let error as InsForgeError {
    switch error {
    case .httpError(let statusCode, let message):
        print("HTTP Error \\(statusCode): \\(message)")
    case .decodingError(let error):
        print("Failed to decode response: \\(error)")
    case .networkError(let error):
        print("Network error: \\(error)")
    default:
        print("Error: \\(error)")
    }
} catch {
    print("Unexpected error: \\(error)")
}
```
