# honey-net

> 目前接口请求响应格式分为两版：

Latest version **1.0.4** (published 2022-05-31) · ISC license · 0 weekly downloads

## Install

```sh
npm install honey-net
pnpm add honey-net
yarn add honey-net
bun add honey-net
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.4 |
| Published | 2022-05-31 |
| First published | 2021-03-16 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 6 |
| Unpacked size | 126.5 KB |
| Known vulnerabilities | 0 (+25 in 2 direct dependencies) |
| Install scripts | no |
| Author | nicolasxiao |
| Maintainers | tinyyue |

## Links

- npm: https://www.npmjs.com/package/honey-net
- Repository: https://git.tencent.com/honey-components/honey-net
- npm.io page: https://npm.io/package/honey-net

## Dependencies (6)

- [uuid](https://npm.io/package/uuid.md) ^8.3.2
- [axios](https://npm.io/package/axios.md) ^0.27.2
- [core-js](https://npm.io/package/core-js.md) ^3.22.7
- [@babel/core](https://npm.io/package/@babel/core.md) ^7.15.0
- [babel-eslint](https://npm.io/package/babel-eslint.md) ^10.1.0
- [regenerator-runtime](https://npm.io/package/regenerator-runtime.md) ^0.13.9

## Recent versions

- 1.0.4 (latest) — 2022-05-31
- 1.0.3 — 2021-12-16
- 1.0.2 — 2021-12-16
- 1.0.1 — 2021-12-16
- 1.0.0 — 2021-03-16

## README

# honey-net 接口请求库

目前接口请求响应格式分为两版：

 1. 旧版：海纳原有所有系统都采用这种格式
 2. 新版：遵循腾讯云apiv3规范

本接口请求库，通过封装，隐藏了不同接口格式的底层细节，提供统一的请求方式，响应结果，只需在初始化时选择对应的接口格式即可

## 安装方法

```bash
npm install --save "honey-net"
```

## 接口库初始化

NetV3是新版接口
NetV1是旧版接口

### 新版接口初始化方法

```javascript
import { NetV3 as Net } from '@tencent/honey-net';
const api = new Net();
api.init({
  baseUrl: '/',
});
```

### 旧版接口初始化方法

```javascript
import { NetV1 as Net } from '@tencent/honey-net';
const api = new Net();
api.init({
  baseUrl: '/',
});
```

### init传入的参数

| 参数名              | 传入值 | 说明                                                                 |
| ------------------- | ------ | -------------------------------------------------------------------- |
| errorHandler        | 函数   | 异常拦截器，除ApiError以外的异常，如网络异常等，返回true则不继续抛出 |
| apiErrorHandler     | 函数   | 异常拦截器，只有ApiError异常会传入，返回true则不继续抛出             |
| customHeaderHandler | 函数   | 自定义header，函数应这么定义 headers => { /* 加上自定义header */}    |
| baseUrl             | url    | 请求接口根路径                                                       |
| timeout             | 毫秒   | 请求超时时间                                                         |
| requestHandlers     | 数组   | 请求处理器，可以传入多个处理函数                                     |
| responseHandlers    | 数组   | 响应处理器，可以传入多个处理函数                                     |
| suspendSyncTime     | 布尔值 | 默认为false                                                          |

## Net对象方法

### NetV3.post

原始的post方法

不会对返回信息进行解析

```javascript
import { NetV3 as Net } from '@tencent/honey-net';
const api = new Net();

const res = await api.post('/v1/getRole', {
  RoleID: 123
})

if (res.data) {
  // res.data 是接口返回的数据，需要自行解析，自行处理正常数据返回或者错误数据返回
}
```

### NetV3.get

原始的get方法

不会对返回信息进行解析

```javascript
import { NetV3 as Net } from '@tencent/honey-net';
const api = new Net();

const res = await api.get('/v1/getRole', {
  RoleID: 123
},{
  headers: {
    xxxx: 'xxx'
  },// 添加请求头等其他自定义参数
})

if (res.data) {
  // res.data 是接口返回的数据，需要自行解析，自行处理正常数据返回或者错误数据返回
}
```

### NetV3.setToken

设置 jwt token 值

```javascript
api.setToken('blah blah');
```

### NetV3.easyPost

post方法

会对返回信息进行解析，如果接口返回正常数据，post函数返回值就是接口Response里的数据，如果接口返回错误，则会抛出ApiError
可通过ApiError的getCode和getMessage分别获得错误码和错误信息

```javascript
import { NetV3 as Net, ApiError } from '@tencent/honey-net';
const api = new Net();

try {
  const res = await api.easyPost('/v1/getRole', {
    RoleID: 123
  })
  // 这里res就是接口返回的正常数据
} catch (err) {
  if (err instanceof ApiError) {
    // 错误码
    const code = err.getCode()
    // 错误信息
    const message = err.getMessage()
  }
}

```

### NetV3.easyGet

get方法

会对返回信息进行解析，如果接口返回正常数据，get函数返回值就是接口Response里的数据，如果接口返回错误，则会抛出ApiError
可通过ApiError的getCode和getMessage分别获得错误码和错误信息

```javascript
import { NetV3 as Net, ApiError } from '@tencent/honey-net';
const api = new Net();

try {
  const res = await api.easyGet('/v1/getRole', {
    RoleID: 123
  })
  // 这里res就是接口返回的正常数据
} catch (err) {
  if (err instanceof ApiError) {
    // 错误码
    const code = err.getCode()
    // 错误信息
    const message = err.getMessage()
  }
}

```

## 错误对象

### ApiError

如果是接口返回的错误信息，easyPost和easyGet会抛出ApiError

ApiError有如下函数可以使用：

| 函数名                             | 函数功能                                                    |
| ---------------------------------- | ----------------------------------------------------------- |
| getCode                            | 获取错误码                                                  |
| getMessage                         | 获取错误描述文案                                            |
| isAuthFailureInvalidSecretId       | 密钥非法（不是云 API 密钥类型）。                           |
| isAuthFailureMFAFailure            | MFA 错误。                                                  |
| isAuthFailureSecretIdNotFound      | 密钥不存在。                                                |
| isAuthFailureSignatureExpire       | 签名过期。                                                  |
| isAuthFailureSignatureFailure      | 签名错误。                                                  |
| isAuthFailureTokenFailure          | token 错误。                                                |
| isAuthFailureUnauthorizedOperation | 请求未 CAM 授权。                                           |
| isDryRunOperation                  | DryRun 操作，代表请求将会是成功的，只是多传了 DryRun 参数。 |
| isFailedOperation                  | 操作失败。                                                  |
| isInternalError                    | 内部错误。                                                  |
| isInvalidAction                    | 接口不存在。                                                |
| isInvalidParameter                 | 参数错误。                                                  |
| isInvalidParameterValue            | 参数取值错误。                                              |
| isLimitExceeded                    | 超过配额限制。                                              |
| isMissingParameter                 | 缺少参数错误。                                              |
| isNoSuchVersion                    | 接口版本不存在。                                            |
| isRequestLimitExceeded             | 请求的次数超过了频率限制。                                  |
| isResourceInUse                    | 资源被占用。                                                |
| isResourceInsufficient             | 资源不足。                                                  |
| isResourceNotFound                 | 资源不存在。                                                |
| isResourceUnavailable              | 资源不可用。                                                |
| isUnauthorizedOperation            | 未授权操作。                                                |
| isUnknownParameter                 | 未知参数错误。                                              |
| isUnsupportedOperation             | 操作不支持。                                                |
| isUnsupportedProtocol              | HTTPS 请求方法错误，只支持 GET 和 POST 请求。               |
| isUnsupportedRegion                | 接口不支持所传地域。                                        |


## 使用Demo

下面以post请求（新版）

假设接口定义如下：

请求路径：

method: POST

path: /v1/GridPCSvr/DescribeRoleList

请求参数：

```json
{
  "RequestId": "xxx",
  "RoleID": "1001",
  "Offset": 0,
  "Limit": 10
}

```

接口返回：

```json
{
  "Response": {
    "TotalNum":143,
    "RoleMemberList":[{
      "UserName":"张三",
      "UserID":"XXX",                    
      "CreateTime":"2020-12-02 19:03:21",
      "Phone":"13923882323",
    }]
  }
}
```

可以如下请求

```javascript
import { NetV3 as Net } from '@tencent/honey-net';
const api = new Net();
api.init({
  baseUrl: '/',
});

async function getRoleList(params) {
  try {
    const roleListData = await api.easyPost('/v1/GridPCSvr/DescribeRoleList', params);

    return roleListData;
  } catch (error) {
    // ApiError 是接口返回错误信息，需要继续抛出去给业务逻辑
    if (error instanceof ApiError) {
      if (error.isAuthFailureTokenFailure()) {
        // token 失效了
        // 处理token失效的逻辑
      } else {
        // 其他错误
        // 如果无法处理则继续抛出错误
        throw error
      }
    }
    console.error(error.message);
  }
  return null;
}

// 这里无需存入RequestId，接口库会自动带上
const resData = await getRoleList({
  "RoleID": "1001",
  "Offset": 0,
  "Limit": 10
})

```

---
_Source: https://npm.io/package/honey-net · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
