# @prequest/response-types-client

> Restful-API 响应的 JSON 数据的 TypeScript 类型生成器

Latest version **1.5.2** (published 2022-07-10) · MIT license · 0 weekly downloads

## Install

```sh
npm install @prequest/response-types-client
pnpm add @prequest/response-types-client
yarn add @prequest/response-types-client
bun add @prequest/response-types-client
```

## Health

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

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.5.2 |
| Published | 2022-07-10 |
| First published | 2021-08-30 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=10 |
| Dependencies | 3 |
| Unpacked size | 18.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 89 |
| Author | xdoer |
| Maintainers | thomas_han |
| Keywords | http, request, XMLHttpRequest, fetch, https, middleware, interceptor |

## Links

- npm: https://www.npmjs.com/package/@prequest/response-types-client
- Repository: https://github.com/xdoer/PreQuest
- Homepage: https://pre-quest.vercel.app
- Issues: https://github.com/xdoer/PreQuest/issues
- npm.io page: https://npm.io/package/@prequest/response-types-client

## Dependencies (3)

- [@prequest/types](https://npm.io/package/@prequest/types.md) ^1.5.2
- [@prequest/helper](https://npm.io/package/@prequest/helper.md) ^1.5.2
- [json-types-generator](https://npm.io/package/json-types-generator.md) ^0.0.5

## Alternatives

- [launchdarkly-js-client-sdk](https://npm.io/package/launchdarkly-js-client-sdk.md) — 2.5M weekly downloads
- [@elastic/elasticsearch](https://npm.io/package/@elastic/elasticsearch.md) — 2.1M weekly downloads
- [@c8y/client](https://npm.io/package/@c8y/client.md) — 15.3K weekly downloads
- [@signaldb/maverickjs](https://npm.io/package/@signaldb/maverickjs.md) — 1.7K weekly downloads
- [@bbc/http-transport-cache](https://npm.io/package/@bbc/http-transport-cache.md) — 1.2K weekly downloads

## Recent versions

- 1.5.2 (latest) — 2022-07-10
- 1.5.1 — 2022-07-03
- 1.5.0 — 2022-06-18
- 1.4.1 — 2022-05-02
- 1.4.0 — 2022-05-02
- 1.3.10 — 2022-04-18
- 1.3.9 — 2022-04-18
- 1.3.8 — 2022-04-17
- 1.3.7 — 2022-04-17
- 1.3.6 — 2022-04-03
- 1.3.5 — 2022-03-09
- 1.3.3 — 2022-02-27
- 1.3.3-alpha.0 — 2022-02-26
- 1.3.2 — 2022-02-09
- 1.2.6 — 2021-12-18
- … 6 more at https://npm.io/package/@prequest/response-types-client/versions

## README

# @prequest/response-types-client

Restful-API 响应的 JSON 数据的 TypeScript 类型生成器

## 安装

```bash
npm install @prequest/response-types-client
```

## 前言

在前端项目中，没有 fs 等 API，导致不能在运行时，动态生成 Restful-API 响应的 JSON 数据的类型文件。

因而我尝试开发了 [@prequest/response-types-generator](https://github.com/xdoer/PreQuest/tree/main/packages/response-types-generator)，它根据配置，可以发起请求和解析响应，最后生成类型文件。但缺点也很明显，需要将要项目中请求的接口一个一个配置到配置文件中。普通的 Get 请求还好说，但对于 Post 请求，一些复杂的传参，也不是很好处理。

本项目解决了上述问题。原理非常简单，首先开启一个 Http Server，然后在前端项目的请求库中间件中，将请求的参数和响应结果，通过一个新的请求实例，发送到 Http Server 中，Http Server 根据传参，利用 fs API 向指定目录生成类型文件即可。

项目分为两部分 [@prequest/response-types-server](https://github.com/xdoer/PreQuest/blob/main/packages/response-types-server) 与 [@prequest/response-types-client](https://github.com/xdoer/PreQuest/blob/main/packages/response-types-client)

## 使用

在发起 HTTP 请求时，中间件会向 `@prequest/response-types-server` 发起生成类型文件的请求

### 配置中间件

```ts
import { create } from '@prequest/xhr'
import generatorMiddleware from '@prequest/response-types-client'

const httpAgent = create({ path: 'http://localhost:10010/' })
const middleware = generatorMiddlewareWrapper({
  enable: process.env.NODE_ENV === 'development',
  httpAgent: httpAgent,
  outPutDir: 'src/api-types',
  typesGeneratorConfig(req, res) {
    const { path } = req
    const { data } = res

    if (!path) throw new Error('path not found')

    const outPutName = path.replace(/.*\/(\w+)/, (_, __) => __)
    const interfaceName = outPutName.replace(/^[a-z]/, g => g.toUpperCase())

    return {
      data,
      outPutName,
      interfaceName,
      overwrite: true,
    }
  },
})

export const prequest = create({ baseURL: 'http://localhost:3000' })
prequest.use(middleware)
```

在小程序项目中使用应当注意，需要配置中间件将真正服务端的响应返回

```ts
import { create } from '@prequest/miniprogram'
import generatorMiddleware, {  } from '@prequest/response-types-client'

const httpAgent = create(wx.request, { path: 'http://localhost:10010/' })

httpAgent.use(async (ctx, next) => {
  await next()
  const { statusCode, data } = ctx.response
  if (statusCode === 200) {
    // 请求需要返回真正的服务器数据
    ctx.response = data
  }
})

const middleware = generatorMiddlewareWrapper({
  enable: process.env.NODE_ENV === 'development',
  httpAgent: httpAgent,
  // 其他参数...
}
```

### 请求参数

上面在生成 `prequest` 实例的时候，类型中提供了 `rewriteType` 参数，可以强制复写已生成的类型文件。即每次请求,都会重新生成一份新的类型文件

```ts
prequest('/user', { rewriteType: true })
```

## 配置

### 中间件参数

| 参数                 | 类型                          | 必填 | 含义                            |
| -------------------- | ----------------------------- | ---- | ------------------------------- |
| enable               | boolean                       | 否   | 开启中间件                      |
| outPutDir            | string                        | 是   | 类型文件输出目录                |
| httpAgent            | PreQuestInstance              | 是   | 发起请求                        |
| typesGeneratorConfig | (req, res) => GeneratorConfig | 是   | json-types-generator 工具的参数 |

### GeneratorConfig

| 参数          | 类型    | 必填 | 含义              |
| ------------- | ------- | ---- | ----------------- |
| data          | Json    | 是   | 要生成类型的 JSON |
| outPutName    | string  | 是   | 类型文件名称      |
| interfaceName | string  | 是   | 导出的接口名称    |
| overwrite     | boolean | 是   | 类型文件可复写    |

---
_Source: https://npm.io/package/@prequest/response-types-client · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
