axios-io-ts
v1.0.1
Published
Axios with io-ts validation
Downloads
45
Readme
Table of Contents
Getting started
NPM install
npm install axios-io-ts
Features
Requests
HTTP request functions can be imported individually e.g.
import { httpPost } from "axios-io-ts"
const promise = httpPost({
url: "/test",
data: {
foo: "bar",
},
})
as part of the default export e.g.
import axios from "axios-io-ts"
const promise = axios.get({
url: "/test",
data: {
foo: "bar",
},
})
or, with the client factory e.g.
import { httpClient } from "axios-io-ts"
const client = httpClient({ baseURL: "baseURL" }) // OR axios.create({ baseURL: "baseURL" })
const promise = client.post({
url: "/test",
data: {
foo: "bar",
},
})
Data validation
Axios response data can be validated by providing an io-ts decoder to your request
import { httpGet } from "axios-io-ts"
import * as t from "io-ts"
const promise = httpGet({
url: "/test",
decoder: t.type({
foo: t.string,
}),
}).then((response) => response.data.foo) // strongly typed foo
Error handling
If data validation fails, a DecodeError
is thrown. You can catch this with onDecodeError()
import { httpGet, onDecodeError } from "axios-io-ts"
import * as t from "io-ts"
const promise = httpGet({
url: "/test",
decoder: t.type({
foo: t.string,
}),
})
.then((response) => response.data.foo)
.catch(onDecodeError((err) => handle(err)))
.catch((other) => null)