本文发表于 471 天前,其中的信息可能已经事过境迁

openapi-typescript-codegen

概述

openapi-typescript-codegen 是一个用于生成 TypeScript 代码的工具,它可以根据 OpenAPI 规范(以前称为 Swagger)自动生成客户端和服务器端代码。

这个工具可以帮助开发人员快速地创建符合 API 规范的 TypeScript 代码,减少手动编写重复代码的工作量。通过使用 openapi-typescript-codegen,开发人员可以更容易地与 API 进行交互,并确保代码的一致性和准确性。

ferdikoomen/openapi-typescript-codegen (github.com)

安装

sh
npm install openapi-typescript-codegen --save-dev

使用

sh
$ openapi --help

  Usage: openapi [options]

  Options:
    -V, --version             output the version number
    -i, --input <value>       OpenAPI specification, can be a path, url or string content (required)
    -o, --output <value>      Output directory (required)
    -c, --client <value>      HTTP client to generate [fetch, xhr, node, axios, angular] (default: "fetch")
    --name <value>            Custom client class name
    --useOptions              Use options instead of arguments
    --useUnionTypes           Use union types instead of enums
    --exportCore <value>      Write core files to disk (default: true)
    --exportServices <value>  Write services to disk (default: true)
    --exportModels <value>    Write models to disk (default: true)
    --exportSchemas <value>   Write schemas to disk (default: false)
    --indent <value>          Indentation options [4, 2, tab] (default: "4")
    --postfixServices         Service name postfix (default: "Service")
    --postfixModels           Model name postfix
    --request <value>         Path to custom request file
    -h, --help                display help for command

  Examples
    $ openapi --input ./spec.json --output ./generated
    $ openapi --input ./spec.json --output ./generated --client xhr

--input:指定接口文档的路径、url 或字符串内容(必填)

--output:代码生成的目录

--client:生成的代码所需要使用的请求库

sh
openapi --input ./knife4j.json --output ./src/spi --client axios

openapi --input http://localhost:8121/api//v2/api-docs --output ./generated --client axios

配置

./core/OpenAPI.ts 是请求的全局配置

  • BASE:请求基地址
  • WITH_CREDENTIALS: false:表示客户端代码中禁用凭据传递,如果需要实现基于cookies的用户登录,需要将其改成 true。