tswagger
TypeScript icon, indicating that this package has built-in type declarations

1.1.4 • Public • Published

TSwagger

TS-Swagger plugin generator CLI
CLI to generate Axios or other API client from Swagger schema

npm package github stars

Installation

npm i -D tswagger

Basic Usage

in project directory

npx tswagger https://petstore3.swagger.io/api/v3/openapi.json

in script code

import { createApi } from './lib/api'
const api = createApi()
const foo = await api.foo.bar(1).post(requestBody) // Post /foo/{bar} 
api.foo.bar.get() // GET /foo/bar

Use fetch or other request library

npx tswagger https://api.server.foo/swagger.json --mode request
import { createApi } from './lib/api'
const fetchApi = createApi((path, method, { params, formData, body }) => {
  const url = new URL(`http://localhost${path}`)
  // url.search = qs.stringify(params, { arrayFormat: 'brackets' })
  return fetch(url, {
    method,
    body: formData ?? (body && JSON.stringify(body)),
  })
}, response => {
  if (response.status >= 400) throw new Error(...)
  return response.json()
})
const {data} = await fetchApi.foo.bar(1).get(2) // GET /foo/{bar} 
fetchApi.foo.bar.get() // GET /foo/bar


import axios, { AxiosError } from 'axios'
const axiosApi = createApi((path, method, { params, formData, body }) =>
  axios({ url: path, method, params, data: formData ?? body }),
  response => response.data)
const {data} = axiosApi.foo.bar(1).get(2)

Options

npx tswagger argument1 --option1 value1 --option2 value2
option description default example
(first argument) Swagger schema JSON path (required) http://.. or ./foo/swagger.json
src same as first argument first argument same as above
mode Code generation mode axios request
path Output path lib/api api.ts
export-name Export name createApi ''(export default)
type-path Path for scheme type file {dir of path}/types.ts ./types/models.ts
tag Tags to generate (All tags) --tag AA --tag BB

Options from file

Options can be an array

tswagger.config.js

// import { TSwaggerOptions } from 'tswagger'
export default { src: '...' } // satisfies Partial<TSwaggerOptions>

package.json

{
  "tswagger": {
    "src": "..."
  }
}

License

ISC License Copyright (c) 2023, Elevista

Package Sidebar

Install

npm i tswagger

Weekly Downloads

109

Version

1.1.4

License

ISC

Unpacked Size

73.4 kB

Total Files

38

Last publish

Collaborators

  • elevista