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

# Client

> SquareCloudAPI 类是 SDK 的入口点。它通过一个 API 密钥实例化，并通过单个客户端暴露每一个模块 —— 应用、数据库、workspace、用户和平台服务。

<Info>
  本页记录的是 **`@squarecloud/api` v4**。如果你正从 v3 升级，请先阅读 [v3 → v4 迁移指南](/zh/sdks/js/migrating_to_v4)。
</Info>

## 要求

* **Node.js 20.0.0** 或更新版本
* 一个有效的 API 密钥 —— 可在 [Square Cloud 控制台](https://squarecloud.app/zh/dashboard)申请

## 安装

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @squarecloud/api
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @squarecloud/api
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @squarecloud/api
    ```
  </Tab>
</Tabs>

## 实例化客户端

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    import { SquareCloudAPI } from "@squarecloud/api";

    const api = new SquareCloudAPI(process.env.SQUARE_API_KEY!);
    ```
  </Tab>

  <Tab title="JavaScript (ESM)">
    ```javascript theme={null}
    import { SquareCloudAPI } from "@squarecloud/api";

    const api = new SquareCloudAPI(process.env.SQUARE_API_KEY);
    ```
  </Tab>

  <Tab title="JavaScript (CommonJS)">
    ```javascript theme={null}
    const { SquareCloudAPI } = require("@squarecloud/api");

    const api = new SquareCloudAPI(process.env.SQUARE_API_KEY);
    ```
  </Tab>
</Tabs>

### 构造函数

| 参数       | 类型       | 是否必填 | 说明                                        |
| -------- | -------- | ---- | ----------------------------------------- |
| `apiKey` | `string` | 是    | 你的 Square Cloud API 密钥。如果它不是字符串，客户端会抛出异常。 |

## 模块

客户端通过专用模块暴露整个 v2 平台。每个模块都是 `SquareCloudAPI` 实例的一个属性。

| 属性                 | 模块                 | 文档                                       |
| ------------------ | ------------------ | ---------------------------------------- |
| `api.user`         | 已认证用户、套餐、拥有的应用和数据库 | 本页                                       |
| `api.applications` | 列出、获取、上传和检查应用      | [管理应用](/zh/sdks/js/managing_application) |
| `api.databases`    | 创建、获取和管理数据库        | [数据库](/zh/sdks/js/databases)             |
| `api.workspaces`   | 创建、列出和管理 workspace | [Workspaces](/zh/sdks/js/workspaces)     |
| `api.service`      | 聚合平台状态             | 本页                                       |
| `api.cache`        | 由 SDK 事件填充的内存缓存    | 本页                                       |

## 获取已认证用户

`api.user.get()` 返回一个 [`User`](https://github.com/squarecloudofc/sdk-api-js/blob/main/src/structures/user.ts) 实例，其中包含账户详情、当前套餐、拥有的应用和拥有的数据库。

```typescript theme={null}
const user = await api.user.get();

console.log(user.id);          // "abcdef0123456789abcdef01"
console.log(user.name);        // "John Doe"
console.log(user.email);       // "john@example.com"
console.log(user.locale);      // "en-US"
console.log(user.plan.name);   // "free" | "standard" | ...
console.log(user.createdAt);   // Date

console.log(user.applications); // Collection<string, BaseApplication>
console.log(user.databases);    // Collection<string, Database>
```

`user.applications` 和 `user.databases` 是 [`Collection`](https://github.com/squarecloudofc/sdk-api-js/blob/main/src/structures/collection.ts) 实例（`Map` 的子类）。可以像操作任何 `Map` 一样遍历它们：

```typescript theme={null}
for (const [id, app] of user.applications) {
    console.log(`${app.name} (${id}) — ${app.ram}MB ${app.language}`);
}
```

## 获取单个应用

使用 `api.applications.fetch(id)` 来检索一个数据完整的 `Application`（当应用带有网站域名时，则为 `WebsiteApplication`）。

```typescript theme={null}
const app = await api.applications.fetch("abc123def456abc123def456");

console.log(app.id, app.name, app.cluster, app.createdAt);

if (app.isWebsite()) {
    // narrowed to WebsiteApplication — `.network` is available
    await app.network.purgeCache();
}
```

旧版的 `api.applications.get(id)` 重载仍然存在，但它返回较轻量的 `BaseApplication`，仅为向后兼容而保留。**在 v4 中请优先使用 `.fetch()`。**

## 列出 snapshot 历史（账户级）

```typescript theme={null}
const appSnapshots = await api.user.snapshots("applications");
const dbSnapshots  = await api.user.snapshots("databases");
```

关于 snapshot 载荷的详情，请参阅 [Snapshots](/zh/sdks/js/snapshots)。

## 平台状态

`api.service.status()` 暴露聚合后的平台健康状况（与公开状态页展示的数据相同）。

```typescript theme={null}
const status = await api.service.status();

console.log(status.status);  // "ok" | "degraded" | "down"
console.log(status.message); // human-readable summary
```

<Note>
  与大多数 v2 端点不同，此路由**不会**将其载荷包裹在标准的 `{ status, response }` 信封中。
</Note>

## 客户端缓存

客户端维护一个内存缓存，SDK 会在你发起调用时使其保持同步：

```typescript theme={null}
api.cache.user;   // last fetched User
// each application instance also exposes app.cache.status / .logs / .snapshots
```

SDK 会发出你可以订阅的类型化事件：

```typescript theme={null}
api.on("userUpdate", (previous, current) => {
    console.log("user changed:", current.name);
});

api.on("statusUpdate", (application, previous, current) => {
    console.log(`${application.name} → ${current.status}`);
});

api.on("logsUpdate", (application, previous, current) => {
    console.log(`new logs for ${application.name}`);
});

api.on("snapshotsUpdate", (application, previous, current) => {
    console.log(`${current.length} snapshots for ${application.name}`);
});
```

## 错误处理

失败的请求会抛出 `SquareCloudAPIError`。该错误暴露一个稳定的 `code` 属性，你可以对其进行 switch 判断以区分不同的失败模式。

```typescript theme={null}
import { SquareCloudAPI, SquareCloudAPIError } from "@squarecloud/api";

try {
    const app = await api.applications.fetch("invalid-id");
} catch (err) {
    if (err instanceof SquareCloudAPIError) {
        console.error(err.code);    // e.g. "APP_NOT_FOUND"
        console.error(err.message);
    }
}
```
