0.1.0-4 • Published 3 years ago

openapi-typescript-client-interface v0.1.0-4

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

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

  • path parameters
  • query parameters

POST

  • path parameters
  • query parameters
  • 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
0.1.0-4

3 years ago

0.1.0-3

3 years ago

0.1.0-2

3 years ago

0.1.0-1

3 years ago

0.1.0-0

3 years ago