openapi-typescript-client-interface

0.1.0-4 • Public • Published

Generate api definitions

  1. Download json file from OpenApi url and convert to TS
npx openapi-typescript http://localhost:8000/openapi.json --output src/apiDefinition.ts
  1. Replace interfaces with types (I am not sure why types work better than interfaces)
sed -Ei '' "s/export interface ([a-zA-Z]*)/export type \1 =/" src/apiDefinition.ts

Usage

import type { AxiosResponse } from 'axios';
import { ApiInterfaceGenerator } from 'openapi-typescript-client-interface';

// import type 'paths' from file generated using openapi-typescript
import { paths } from './apiDefinition';

// let the library compute interface by paths
type ApiInterface = ApiInterfaceGenerator<paths>

// implement the interface (this could also be done using es6 Proxy dynamicaly however Proxy is not correctly typed in TS yet)
const api: ApiInterface = {
  '/': {
    get: (): Promise<AxiosResponse<{ pageTitle: string }>> => {
      return axios.get('/')
    },
  },
}

// TS can determine available methods under each route, parameters, body and even response type
// only reject type can't be infered because TS can't handle it right now https://stackoverflow.com/a/50071254/3265676
api['/'].get().then(({ pageTitle }) => {
  console.log(pageTitle);
})

Method and parameter support:

GET

  • [x] path parameters
  • [x] query parameters

POST

  • [x] path parameters
  • [x] query parameters
  • [x] request body

PUT

  • [ ] method itself
  • [ ] path parameters
  • [ ] query parameters
  • [ ] request body

PATCH

  • [ ] method itself
  • [ ] path parameters
  • [ ] query parameters
  • [ ] request body

DELETE

  • [ ] method itself
  • [ ] path parameters
  • [ ] query parameters

Readme

Keywords

none

Package Sidebar

Install

npm i openapi-typescript-client-interface

Weekly Downloads

0

Version

0.1.0-4

License

ISC

Unpacked Size

13.4 kB

Total Files

9

Last publish

Collaborators

  • insoftcz