0.9.9 • Published 1 year ago

@pluve/fetch v0.9.9

Weekly downloads
30
License
ISC
Repository
-
Last release
1 year ago

@pluve/fetch

@pluve/fetch 基于 fetch 封装网络请求。在低版本浏览器环境中时注意兼容处理。一般可使用 polyfill-io

安装

npm install @pluve/fetch -S

使用说明

@pluve/fetch 支持自定义请求头,可动态设置鉴权 token,实现了请求和响应结果拦截器,可对响应报文统一处理。支持超时时间配置,debug 模式等。目前仅支持 GET、POST 方式。

setDebug

设置是否为 debug 模式。debug 模式下,控制台会打印详细的接口请求及响应信息,默认为关闭,可在开发测试模式下开启。避免影响性能,建议在生产环境关闭。

import FetchAgent from '@pluve/fetch';
FetchAgent.setDebug(true);

setTimeout

设置超时时间,默认为 15s,单位为毫秒

FetchAgent.setTimeout(15000);

setupDefaultGlobalHeaderGenerator

设置统一请求头信息,若某个接口请求头有特殊要求,可在 GET、POST 方法中设置

FetchAgent.setupDefaultGlobalHeaderGenerator(() => new Object());

setupDefaultCommonReqBodyGenerator

在请求体中设置通用参数,如鉴权信息等

FetchAgent.setupDefaultCommonReqBodyGenerator(() => new Object());

setupReqInterceptor

接口请求拦截器,返回 false 则不拦截请求。

FetchAgent.setupReqInterceptor((req: IRequestParam) => false);

setupRespInterceptor

响应结果拦截器,返回 false 则不拦截响应。可应用 token 过期等场景。

FetchAgent.setupRespInterceptor((response: any) => false);

IRequestParam

请求参数说明

interface IRequestParam {
  url: string; // 接口请求链接
  method?: 'GET' | 'POST'; // 请求参数
  headers?: Headers | {}; // 请求头
  body?: any; // 请求体,通常情况传JSON对象即可,支持application/json 和  application/x-www-form-urlencoded
  submitDataType?: 'json' | 'form'; // 数据提交类型
  timeout?: number; // 超时时间
  [key: string]: any;
}

GET

发送 get 请求,返回 Promise

FetchAgent.get({ url: 'url' }); // // 返回Promise<any>

POST

发送 post 请求,返回 Promise

FetchAgent.post({url, {bodyInfo: 'bodyInfo'}); // 返回Promise<any>

// raw json方式提交
const body = { pageNo: 1, pageSize: 10 };
const headers = { Authorization: `token` };
const params = { url, headers, body, submitDataType: 'json' };
const resp = await FetchAgent.sendPost(params);

// FormData 方式提交
const body = { key: 'value' };
const headers = { Authorization: `token` };
const params = { url, headers, body, submitDataType: 'form' };
const resp = await FetchAgent.sendPost(params);

在 react 中使用示例

/**
 * title: @pluve/fetch
 * order: 2
 * desc: 使用```@pluve/fetch``` 处理网络请求,在vue项目中使用类似.
 **/

import React, { useReducer, useEffect } from 'react';
import { Button } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import FetchAgent from '@pluve/fetch';
import 'antd/dist/antd.css';

interface IFetchProps {
  fetchResult: string;
  loading: boolean;
}

FetchAgent.setDebug(true);

const init = (initialValue: string) => {
  return { fetchResult: initialValue || '请点击发送请求', loading: false };
};

const reducer = (state: IFetchProps, action: { type: 'fetch' | 'reset' | 'loading'; payload: any }) => {
  console.log('action -> ', action);
  switch (action.type) {
    case 'loading':
      return { ...state, ...action.payload };
    case 'fetch':
      return { ...state, fetchResult: action.payload };
    case 'reset':
      return init(action.payload || '请点击发送请求');
    default:
      throw new Error();
  }
};

const fetchData = async dispatch => {
  dispatch({ type: 'loading', payload: { fetchResult: '', loading: true } });
  try {
    const resp = await FetchAgent.get({ url: 'https://xxx.yyy.com/zzz' });
    dispatch({ type: 'fetch', payload: JSON.stringify(resp[0]) });
  } catch (e) {
    console.log('fetchData error: ', e);
    dispatch({ type: 'fetch', payload: `error${e}` });
  } finally {
    dispatch({ type: 'loading', payload: { loading: false } });
  }
};

const SmartFetchDemo: React.FC<IFetchProps> = ({ initialValue }) => {
  const [state, dispatch] = useReducer(reducer, initialValue, init);
  useEffect(() => {
    console.log('state update -> ', state);
    return () => {
      console.log('effect clean up ...');
    };
  }, [state]);
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: '1rem' }}>
        <Button type="primary" onClick={() => fetchData(dispatch)}>
          Fetch
        </Button>
        <Button style={{ marginLeft: '1rem' }} onClick={() => dispatch({ type: 'reset' })}>
          Reset
        </Button>
      </div>
      FetchResult: {state.fetchResult}
      {state.loading ? <LoadingOutlined /> : undefined}
    </>
  );
};

export default SmartFetchDemo;

外部依赖

若低版本浏览器需要依赖 whatwg-fetch

issues 说明

暂无版本计划

0.9.9

1 year ago

0.9.8

1 year ago

0.9.7

1 year ago

0.9.6

1 year ago

0.9.4

2 years ago

0.9.3

2 years ago

0.9.5

2 years ago

0.9.2

2 years ago

0.9.1

2 years ago

0.9.0

2 years ago

0.8.9

2 years ago

0.8.8

2 years ago

0.8.5

2 years ago

0.8.4

2 years ago

0.8.7

2 years ago

0.8.6

2 years ago

0.8.3

3 years ago

0.8.2

3 years ago

0.8.1

3 years ago

0.8.0

3 years ago

0.5.2

3 years ago

0.5.1

3 years ago

0.1.2

3 years ago

0.2.0

3 years ago

0.1.1

3 years ago

0.1.0

4 years ago

0.0.14

4 years ago

0.0.13

4 years ago

0.0.12

4 years ago

0.0.10

4 years ago

0.0.11

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago