# 介绍

![badge](https://cnb.cool/cnb/sdk/node-cnb/-/badge/git/1876ef5f/ci/pipeline-as-code)
![badge](https://cnb.cool/cnb/sdk/node-cnb/-/badge/git/latest/ci/status/pull_request)
![badge](https://cnb.cool/cnb/sdk/node-cnb/-/badge/git/1876ef5f/ci/status/tag_push)
![badge](https://cnb.cool/cnb/sdk/node-cnb/-/badge/git/latest/code/vscode-started)
![badge](https://img.shields.io/npm/v/node-cnb.svg)

node-cnb 是一个用于访问 [CNB API](https://api.cnb.cool/) 的 node 编写的 SDK。

## 安装

```shell
npm install node-cnb
```

## 使用

```typescript
import { getClient } from "node-cnb";

// 参数分别为 api url 和 访问令牌
const client = getClient("https://api.cnb.cool", "xxx");

client.users.pinnedRepos
  .list({
    username: "xxx",
  })
  .then((res) => {
    console.log(res);
  });
```

```javascript
const sdk = require("node-cnb");

// 参数分别为 api url 和 访问令牌
const client = sdk.getClient("https://api.cnb.cool", "xxx");

client.users.pinnedRepos
  .list({
    username: "xxx",
  })
  .then((res) => {
    console.log(res);
  });
```

## 方法路径

方法路径有两种模式

### 1.请求路径拼接

方法路径为由如下几个元素组成：

1. 第一个 `/-/` 前的参数名
2. 其他非参数名
3. http method（若 method 为 get 且返回结果为数组则为 list）

例如：

`/{repo}/-/git/branches` 的路径下 get 请求的方法名为 `repo.git.branches.list`

`/{repo}/-/git/branches/{branch}` 的路径下 get 请求方法名为 `repo.git.branches.get`

对于此规则下方法路径仍然重复的 api，则单独定义在 [pathMethodMap.json](https://cnb.cool/cnb/sdk/node-cnb/-/blob/main/pathMethodMap.json)

### 2.Tag+operationId拼接

在 swagger json 中可以看到每个方法都有一个 Tag 和 operationId，

可以用 `client.<Tag>.<operationId>` 调用：

```javascript
const sdk = require("node-cnb");

// 参数分别为 api url 和 访问令牌
const client = sdk.getClient("https://api.cnb.cool", "xxx");

client.Repositories.GetPinnedRepoByID({
    username: "xxx",
  })
  .then((res) => {
    console.log(res);
  });
```

完整api路径请参考 [client.d.ts](https://cnb.cool/cnb/sdk/node-cnb/-/blob/main/src/client.d.ts)

## 错误处理

SDK 统一处理 HTTP 错误响应，返回结构化的错误对象而非抛出异常：

```typescript
interface DieWebError {
  errcode: number;    // HTTP 状态码
  errmsg: string;     // HTTP 状态文本
  errparam: any;      // 响应体内容（如果可解析为 JSON）
}

// 调用示例
const result = await client.users.pinnedRepos.list({ username: "xxx" });
if (isDieWebError(result)) {
  console.error(`请求失败: ${result.errcode} - ${result.errmsg}`);
  return;
}
// 正常处理 result
```

**注意**：非成功状态码（4xx/5xx）不会抛出异常，调用方需自行判断返回值是否为错误对象。可使用 `isDieWebError(result)` 进行类型守卫判断。
