1.0.1 • Published 5 years ago

@ztrehagem/definitively-axios v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

@ztrehagem/definitively-axios

HTTP client with type-safe response through axios.

Usage

Import.

import definitively, { DefinitivelyResponse } from '@ztrehagem/definitively-axios'

You can create some instances like axios.

const instance = definitively.create({
  validateStatus: (status) => status < 500,
})

Declare probable schemas in the data of HTTP response.

interface SchemaA { hoge: string }
interface SchemaB { fuga: number }

Declare probable patterns of the HTTP response as a pair of status code and schema. Note that the available status code is able to be changed by validateStatus.

type DefinitivelyA = DefinitivelyResponse<200 | 201, SchemaA>
type DefinitivelyB = DefinitivelyResponse<400, SchemaB>

Execute HTTP request with the patterns.

const response = await instance.get<DefinitivelyA | DefinitivelyB>('/mock')

If you use switch or if statement with each the status codes, the schema of response is inferred! Note that response.status is also inferred to <200 | 201 | 400> in this case.

switch (response.status) {
  case 200:
  case 201:
    response.data //=> <SchemaA>
    break
  case 400:
    response.data //=> <SchemaB>
    break
}

See example.ts for entire of the sample code.

1.0.1

5 years ago

1.0.0

5 years ago