> ## 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)")
}
```
