@zb81/req
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

@zb81/req

npm version npm downloads bundle JSDocs License

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)

License

MIT License © 2024-PRESENT Zhu Bei

Package Sidebar

Install

npm i @zb81/req

Weekly Downloads

1

Version

0.1.0

License

MIT

Unpacked Size

11.1 kB

Total Files

8

Last publish

Collaborators

  • zb81