@zb81/req
v0.1.0
Published
Axios with class, TypeScript supported.
Downloads
1
Readme
@zb81/req
Quick Start
1. Create an instance
import Request from '@zb81/req' // or import { Request } from '@zb81/req'
// biz error message
const ERROR_MSG = 'That\'s bad...'
// Instantiate with config and interceptors
const request = new Request({
baseURL: 'https://httpbin.org',
timeout: 10000,
responseInterceptor(response) {
if (Math.random() > 0.1) // biz error code
throw new Error(ERROR_MSG) // you can throw the error, or show messages
return response.data
},
})
2. Declare types and req fn
interface Root<P> {
args: P
headers: Headers
origin: string
url: string
}
interface Headers {
'Accept': string
'Accept-Encoding': string
'Host': string
'User-Agent': string
'X-Amzn-Trace-Id': string
}
function getRes(params: IParams) {
return request.get<Root<IParams>>('/get', { params })
}
3. Invoke with type and await-to-js
import to from 'await-to-js'
const [res, err] = await to(getRes({ foo: 'bar' }))
if (!err)
expect(res.args.foo).toBe('bar') // 🚀
else
expect(err.message).toBe(ERROR_MSG)