3.3.1 • Published 2 months ago

typed-axios-instance v3.3.1

Weekly downloads
-
License
ISC
Repository
github
Last release
2 months ago

Typed Axios typed-axios-instance

npm.io

Typed Axios Instance is a simple way to create an Axios instance that is fully typed with the routes from an API.

The benefit of using TypedAxiosInstance is you don't need to create or import a client for a third party API, you can just apply types (generated from OpenAPI or Nextlove) to an existing Axios instance.

import type { TypedAxios } from "typed-axios-instance"
import axios from "axios"

// Need help generating these routes? You can generate them from...
// nextlove: https://github.com/seamapi/nextlove
// openapi: TODO
type Routes = [
  {
    route: "/things/create"
    method: "POST"
    jsonBody: {
      name?: string | undefined
    }
    jsonResponse: {
      thing: {
        thing_id: string
        name: string
        created_at: string | Date
      }
    }
  }
]

const myAxiosInstance: TypedAxios<Routes> = axios.create({
  baseURL: "http://example-api.com",
})

// myAxiosInstance now has intelligent autocomplete!

npm.io

npm.io

Installation

npm add --dev typed-axios-instance

# yarn add --dev typed-axios-instance

Route Definition

There are two ways of specifying routes for TypedAxios<Routes>

  • type Routes = RouteDef[]
  • type Routes = { [route:string]: RouteDef }

Using RouteDef[] allows you to do HTTP Method Discrimination and is the recommended method.

This is the type for RouteDef:

export type RouteDef = {
  route: string
  method: HTTPMethod // you can supply multiple e.g. `"PATCH" | "POST"`

  // INPUTS
  queryParams?: Record<string, any>
  jsonBody?: Record<string, any>
  commonParams?: Record<string, any>
  formData?: Record<string, any>

  // RESPONSES
  jsonResponse?: Record<string, any>
}

HTTP Method Discrimination

There are two ways of specifying route definitions, if you specify the route definitions as an array (default for OpenAPI schemas), you'll get more specific autocomplete results, e.g. the response or request type will be based on what method is being used.

3.3.1

2 months ago

3.3.0

3 months ago

3.2.0

3 months ago

3.1.0

8 months ago

3.0.0

9 months ago

1.0.13

10 months ago

2.0.0

9 months ago

1.0.12

1 year ago

1.0.11

1 year ago

1.0.10

1 year ago

1.0.9

1 year ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.0

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago