概览
Keq 提供的命令行工具可以将 swagger 文档编译为 typescript 代码。从而能像调用函数一样发送 HTTP 请求。
安装
- npm
- pnpm
- yarn
建议在 package.json 锁定 @keq-request/cli 的版本。
@keq-request/cli 的小版本升级为了修复 Bug 可能会修改代码模板。这有极小的概率导致代码不向前兼容。
使用方法
首先,我们需要一份 swagger 文档,例如下面的 cat-service-swagger.json 文件,描述了一个获取猫咪信息的 HTTP 接口。
cat-service-swagger.json
{
"openapi": "3.0.0",
"info": {
"title": "Cat Service",
"version": "0.0.1"
},
"paths": {
"/cats": {
"get": {
"operationId": "getCats",
"parameters": [
{
"name": "breed",
"required": false,
"in": "query",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Cat"
}
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Cat": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "number"
}
}
}
}
}
}然后,我们创建 @keq-request/cli 的配置文件,指定 swagger 文档的位置和编译参数:
- Typescript
- Javascript
- YAML
import { defineKeqConfig, FileNamingStyle } from "@keq-request/cli"
export default defineKeqConfig({
outdir: "./src/apis", // 编译结果的输出目录
fileNamingStyle: FileNamingStyle.snakeCase,
modules: {
catService: "./cat-service-swagger.json",
// 也可以从网络上获取 swagger 文档,例如:
// dogService: "http://dog.example.com/swagger.json"
},
})const { defineKeqConfig, FileNamingStyle } = require("@keq-request/cli")
module.exports = defineKeqConfig({
outdir: "./src/apis", // 编译结果的输出目录
fileNamingStyle: FileNamingStyle.snakeCase,
modules: {
catService: "./cat-service-swagger.json",
// 也可以从网络上获取 swagger 文档,例如:
// dogService: "http://dog.example.com/swagger.json"
},
})outdir: ./src/apis # 编译结果的输出目录
fileNamingStyle: snake_case
modules:
catService: ./cat-service-swagger.json
# 也可以从网络上获取 swagger 文档,例如:
# dogService: http://dog.example.com/swagger.json优先使用 typescript 或 javascript 格式的配置文件。一些高级功能(例如 operationIdFactory)只能通过代码实现。
接下来,在终端执行以下命令:
- npm
- pnpm
- yarn
执行完成后,@keq-request/cli 会在 ./src/apis/cat_service/ 目录下生成如下文件:
- 请求函数
- 接口类型定义
- 数据模型定义
import { Keq } from "keq"
import { request } from '../../request'
import type { GetCatsOperation, GetCatsResponseBodies, GetCatsRequestParameters } from "../types/operations/get_cats.type.js"
export type { GetCatsRequestQuery, GetCatsRequestHeaders, GetCatsRequestBodies } from "../types/operations/get_cats.type.js"
const moduleName = "catService"
const method = "get"
const pathname = "/cats"
export function getCats<STATUS extends keyof GetCatsResponseBodies, CONTENT_TYPE extends never = never>(args?: GetCatsRequestParameters): Keq<GetCatsOperation<STATUS, CONTENT_TYPE>> {
const req = request.post<GetCatsResponseBodies[STATUS]>("/cats")
.option('module', { name: moduleName, pathname, method })
if (args && "breed" in args) req.query("breed", args["breed"], {"arrayFormat":"repeat"})
return req
}
getCats.pathname = pathname
getCats.method = methodimport type { KeqOperation, KeqPathParameterInit, KeqQueryInit, ServerSentEvent } from "keq"
import type { Cat as CatSchema } from "../components/schemas/cat.schema.js"
export interface GetCatsResponseBodies {
200: CatSchema[] | CatSchema[]
}
export interface GetCatsRequestBodies {}
export type GetCatsRequestQuery = {
"breed"?: string
}
export type GetCatsRouteParameters = {}
export type GetCatsRequestHeaders = {}
export type GetCatsRequestParameters = GetCatsRequestQuery & GetCatsRouteParameters & GetCatsRequestHeaders
export interface GetCatsOperation<STATUS extends keyof GetCatsResponseBodies, CONTENT_TYPE extends string > extends KeqOperation {
requestParams: GetCatsRouteParameters & { [key: string]: KeqPathParameterInit }
requestQuery: GetCatsRequestQuery & { [key: string]: KeqQueryInit }
requestHeaders: GetCatsRequestHeaders & { [key: string]: string | number }
requestBody: object | BodyInit
responseBody: GetCatsResponseBodies[STATUS]
}export interface Cat {
"name"?: string
"age"?: number
}这样,我们就可以调用 getCats 函数来发送 HTTP 请求:
import { getCats } from "./src/apis/cat_service/operations"
const cats = await getCats({ breed: "siamese", unknownKey: 'value' }) // unknownKey 未在 swagger 定义,将被丢弃
.retry(3, 1000)
.timeout(1000)
// 追加额外的请求参数
.query('extraQuery', 'extra')
.set('Authorization', 'TOKEN')
.send({ extraBody: 'extra' })
// 实际请求地址: /cats?breed=siamese&extraQuery=extra
console.log(`我的猫咪有:${cats.map(cat => cat.name).join('、')}`)
console.log(`请求路径:${getCats.pathname}`)BodyFallbackPlugin 可以将 unknownKey 这样的未定义请求参数,全部添加到请求体中。最后,我们可以为 catService 模块的所有接口添加统一的错误处理逻辑:
import { request } from './api/request'
import { throwException, RequestException } from 'keq-exception'
request
.useRouter()
.module('catService', throwException(context => {
if (context.response) {
if (context.response.status >= 400 && context.response.status < 500) {
throw new RequestException(context.response.status, context.response.statusText, false) // 客户端错误,不需要重试
} else if (context.response.status >= 500) {
throw new RequestException(context.response.status, context.response.statusText)
}
}
}))Keq 采用 链式调用 + 中间件 的设计模式?Keq 最初就是为了从 swagger 文档生成请求函数而设计的。然而,只依赖cli 生成代码,许多问题是无法解决的:
swagger文档中定义的 HTTP 接口信息可能是不完整的,甚至是错误的,例如缺少认证信息、缓存策略等参数。 可偏偏一些外部因素阻止我们通过修改swagger文档来补全这些信息。- 客户端在不同场景下调用同一个 HTTP 接口时,可能会有不同的需求,例如在某些场景下需要重试,而在另一些场景下则不需要。
静态生成的代码无法满足这些动态变化的需求。 - 同一个
swagger文档的接口往往有着类似的鉴权、错误处理、日志记录等复杂的需求。这些高度定制化的功能如果使用cli的Plugin生成会非常难以维护。
Keq 便是为给予静态生成代码提供更强大的运行时 API 而设计的 HTTP 客户端:
- 链式调用 让我们在调用
请求函数时,可以动态的修改请求参数,甚至设置违背swagger定义的参数。并且它完美地避免了臃肿的配置选项。 - 中间件 则提供了一种优雅的方式来为同一模块的所有接口添加统一的功能。并可以通过 链式调用 在不同场景下灵活的启用或禁用 中间件。
配置文件
.keqrc.(yml|json|js|ts)
@keq-request/cli 会自动查找名为 .keqrc.yml、.keqrc.json、.keqrc.js、.keqrc.ts的配置文件。
你可以通过 -c --config <config_file_path> 设置配置文件地址。
| 配置参数 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|
| outdir | true | - | 编译结果的输出目录 |
| modules | true | - | Swagger 文件地址和模块名称 |
| fileNamingStyle | false | - | 文件名风格 |
| mode | false | micro-function | 生成的代码风格 |
| esm | false | 若 package.json 是否设置了 "type": "module" 则为 true | 是否生成 ESM 风格的代码 |
| plugins | false | [] | 插件向第三方开发者提供了完整的自定义 cli 行为的能力 |
fileNamingStyle
| 枚举 | 示例 |
|---|---|
FileNamingStyle.camelCase | "twoWords" |
FileNamingStyle.capitalCase | "Two Words" |
FileNamingStyle.constantCase | "TWO_WORDS" |
FileNamingStyle.dotCase | "two.words" |
FileNamingStyle.headerCase | "Tow-Words" |
FileNamingStyle.noCase | "two words" |
FileNamingStyle.paramCase | "two-words" |
FileNamingStyle.pascalCase | "TwoWords" |
FileNamingStyle.pathCase | "two/words" |
FileNamingStyle.sentenceCase | "Two words" |
FileNamingStyle.snakeCase | "two_words" |
mode
| 枚举 | 描述 |
|---|---|
micro-function | 生成函数形式的 API 调用代码 |
nestjs-module | 生成适用于 NestJS 的模块代码 |
.keqignore
还可以通过 .keqignore 文件忽略不需要生成代码的 HTTP 接口:
# 格式为
# [moduleName] [method] [pathname]
* * * # 忽略所有模块的所有接口
* GET /cats # 忽略所有模块的 GET /cats 接口
* GET * # 忽略所有模块的 GET 接口
catService * /cats # 忽略 catService 模块的 /cats 接口
catService GET /cats # 忽略 catService 模块的 GET /cats 接口
! dogService POST /dogs # 不忽略 dogService 模块的 POST /dogs 接口命令
keq build [options]
按照配置文件的内容,生成代码。
| 选项 | 描述 |
|---|---|
--modules <moduleName...> | 仅生成匹配模块名称的模块 |
-c --config <config_file_path> | 配置文件的地址 |
-i --interactive | 通过命令行交互,指定需要生成的 HTTP 接口 |
--tolerant | 忽略 Swagger 格式错误,尽可能生成代码 |
--method <method...> | 仅生成匹配 method('get' | 'post' | 'put' | 'patch' | 'head' | 'options' | 'delete') 的 HTTP 接口 |
--pathname <pathname...> | 仅生成匹配 pathname 的 HTTP 接口 |
keq ignore <mode> [options]
添加忽略规则到 .keqignore 文件。使用 --interactive 可以通过命令行交互指定需要忽略的 HTTP 接口。
| 选项 | 描述 |
|---|---|
<mode> | add:添加忽略规则,except:添加不忽略规则 |
-c --config <config_file_path> | 配置文件的地址 |
--modules | 设置添加的忽略规则的模块名称 |
--method <method> | 设置添加的忽略规则的 HTTP 方法('get' | 'post' | 'put' | 'patch' | 'head' | 'options' | 'delete') |
--pathname <pathname...> | 设置添加的忽略规则的 HTTP 接口路径 |
-i --interactive | 通过命令行交互,指定需要忽略的 HTTP 接口 |
--build | 忽略规则添加完成后,自动执行 keq build 命令生成代码 |