buping_fetch
TypeScript icon, indicating that this package has built-in type declarations

1.1.3 • Public • Published

@core/fetch

1. 介绍

基于 fetch 的通用请求库;

2. 安装

yarn add @core/fetch
npm install @core/fetch

3. 使用

3.1 基本使用

import http from '@core/fetch'

// http 支持两种形式。
// 1. method在config中配置
const { success, RetCode } = await http(url, {
  method: 'GET',
  body: {},
  codeKey: 'codeKey', // 接口返回的用于判断是否成功的 code 键值,通常不需要传,底层会默认先去找接口是否返回 'RetCode' 或 'retCode'
  dataType: 'hlj', // 默认值为 hlj,底层会对请求返回做一次统一转换,如需拿到接口原始返回,传 'json'
  expect: {}, // 期望值,当接口 data 值返回 undefined 或 null 时使用期望值,默认为空对象
})

// 2. 通过方法调用,支持get、post、put、delete
await http.get(url, config)
await http.post(url, config)
await http.put(url, config)
await http.delete(url, config)

or

import { createApi } from '@core/fetch'

const getDetail = createApi(url, config)

// 也支持方法调用,支持get、post、put、delete
const getDetail2 = createApi.get(url, config)
const postDetail = createApi.post(url, config)
const putDetail = createApi.put(url, config)
const deleteDetail = createApi.delete(url, config)

const { success, RetCode } = await getDetail({ id: xxx })

createApi 返回的是函数,需要再次传入 body 参数。http直接在 config 中配置 body。

createApihttp 两者都具有泛型 TData 用于标识响应体中 data 字段的类型,默认为any,使用如下

import { createApi } from '@core/fetch'

let data?: number
data = await createApi<string>(url, config) // 类型不匹配,data 不可以赋值为string
data = await http<number>(url, config) // 正确

3.2 全局配置

在项目的入口处,最好是 index.js 中,使用 configure 方法设置全局的配置。

configure({ config, ...rest })

config 属性是一个函数,处理默认配置项。其余属性默认合并至配置项。

使用:

import { message } from 'antd'
import { configure } from '@core/fetch'

configure({
  config: (config) => {
    config.headers['login-as'] = 'main'
    // 必须返回 config
    return config
  },
  // 如配置了此参数,全局错误码返回不为 0 时会调用该回调函数
  onError: (Retcode, msg) => {
    message.warn(msg)
  },
})

4. 配置项

相关配置项参考 fetch

config ts 类型

  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  body?: TBody
  dataType?: 'hlj' | 'json' | 'text'
  bodyType?: 'json' | 'file' | 'form'
  codeKey?: string
  ignore?: any[]
  onError?: ((RetCode, msg) => void) | null | false
  onSuccess?: ((RetCode, msg) => void) | null | false
  expect?: any
  transformUrl?: ((url, requestInit) => string) | false
  beforeRequest?: ((url, config) => object) | false
  transformRequest?: ((body: TBody) => TBody) | false

4.1 请求配置项

method

method?: 'GET' | 'POST' | 'PUT' | 'DELETE'

请求方法,默认为 GET。

方法为 GET 和 DELETE 类型时,会转换 body 参数,将参数拼接到 url 上。

bodyType

bodyType?: 'json' | 'file' | 'form'
  1. bodyType 类型为 form 时,会转换 body 参数,处理成参数拼接的字符串形式。

    headers 中的 Content-Type 为application/x-www-form-urlencoded;charset=utf-8

  2. bodyType 类型为 file 时,会转换 body 参数,处理成 formData 对象格式。

  3. 否则,将 body 参数处理成 JSON 字符串。

import { createApi } from '@core/fetch'

createApi.post(url, {
  body: {
    file: document.querySelector('input[type=file]').files[0],
    otherKey: value,
  },
  bodyType: 'file', // 需指定 bodyType: 'file'
})

transformRequest

transformRequest?: ((body: object) => object) | false

传入参数为配置项 body,可以自行转换 body,返回需要的 body 格式。

transformUrl

transformUrl?: ((url, config) => string) | false

转换 url 参数,config 为传入的 fetch 支持的配置参数。

beforeRequest

beforeRequest?: ((url, headers) => object) | false

beforeRequest 会转换传入的 headers 参数

ignore

ignore?: any[]

剔除 body 中某些属性,剔除的属性的值是 ignore 数组中的元素。 ignore 默认值是[null, undefined, '']

例:

http.post('xxx', {
  body: {
    name: '',
    id: undefined,
    age: 18,
  },
  ignore: [null, undefined, ''],
})

会将 body 中 name 和 id 属性剔除,最终的 body 为{age: 18}

4.2 响应配置项

expect

expect?: any

期望值,默认为空对象。

  1. dataType 为 hlj 时,当接口 data 值返回 undefined 或 null 时使用期望值

  2. 请求失败时的 data 值。

codeKey

codeKey?: string

接口返回的 code 键,用于判断是否成功的 ,通常不需要传,底层会默认先去找接口键值是否有 'RetCode' 或 'retCode',没有则默认为'code'。

dataType

dataType?: 'hlj' | 'json' | 'text'

默认值为 hlj,底层会对请求返回做一次统一转换,如需拿到接口原始返回,传 'json'

dataType 为 hlj 时,返回的结果格式如下:

export interface IFetchResponse<TData = any> {
  data: TData
  msg: string
  msgSuccess: string
  success: boolean
  RetCode: number
}

msg、msgSuccess 是接口返回的 msg、msgSuccess 值。

data 是接口返回的 data 值,若没有 data 值,会默认为传入的 expert 参数。

RetCode 是接口返回的 code 键值。

一般项目中后端接口返回 RetCode0 表示接口请求成功,获取请求是否成功只要用返回的 success 判断即可。

onError

onError?: ((RetCode, msg) => void) | null | false

dataType 为 hlj 时,接口失败(code 值不为 0)的回调,msg 为接口返回的 msg 值。

onSuccess

onSuccess?: ((RetCode, msgSuccess) => void) | null | false

dataType 为 hlj 时,接口成功的回调,msgSuccess 为接口返回的 msgSuccess 值。

4.3 默认配置

const defaultConfig = {
  method: 'GET',
  body: {},
  dataType: 'hlj',
  bodyType: 'json',
  codeKey: '',
  ignore: [null, undefined, ''],
  onError: false,
  expect: {},
  transformUrl: false,
  beforeRequest: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json;charset=utf-8',
  },
  credentials: 'include',
}

5. 开发 & 发布

源码在 src 目录下,开发完后需要写测试用例,在 test 目录下。测试完毕后需要先执行 yarn build 构建出生产文件,然后使用 npx lerna publish 进行发布。

Readme

Keywords

none

Package Sidebar

Install

npm i buping_fetch

Weekly Downloads

1

Version

1.1.3

License

MIT

Unpacked Size

67.1 kB

Total Files

39

Last publish

Collaborators

  • buping