3.0.0 • Published 9 months ago

@rayb/ray-fetch v3.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

ray-fetch

author

ilex.h

useage

npm install ray-fetch

  • rayfetch

高级使用

// web
import _RayFetch from '@rayb/ray-fetch/lib/rayfetch';

// create instance
const RayFetch = new _RayFetch({
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=utf-8'
  }
});

// 使用
RayFetch.del(url, {params, data}).then(res => res);
RayFetch.get(url, {params, data}).then(res => res);
RayFetch.head(url, {params, data}).then(res => res);
RayFetch.options(url, {params, data}).then(res => res);
RayFetch.post(url, {params, data}).then(res => res);
RayFetch.put(url, {params, data}).then(res => res);

// --- 高级使用 ---

// 1. 统一处理发送数据,用于 sign 校验

const RayFetch2 = new _RayFetch({
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=utf-8'
  },
  beforeSend: ({ url, method, params, data }) => {
    if (method === 'GET'){
      // do someThing
    } else {
      // encode data
    }

    return {
      url, params, data
    };
  }
});

// 2. 自定义子类

class YourFetch extends _RayFetch {
  constructor(){
    super({
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json; charset=utf-8'
      },
      beforeSend: ({ url, method, params, data }) => {
        if (method === 'GET'){
          // do someThing
        } else {
          // encode data
        }

        return {
          url, params, data
        };
      }
    });
  }
}

// 使用
const myFetch = new YourFetch();
myFetch.del(url, {params, data}).then(res => res);
myFetch.get(url, {params, data}).then(res => res);
myFetch.head(url, {params, data}).then(res => res);
myFetch.options(url, {params, data}).then(res => res);
myFetch.post(url, {params, data}).then(res => res);
myFetch.put(url, {params, data}).then(res => res);
  • rayrequest
// web
import rayRequest from '@rayb/ray-fetch/lib/rayrequest';

// DELETE GET HEAD OPTIONS POST PUT

// 使用
rayRequest(url, {
  method: 'POST',
  headers: headers, // 可选
  body: params, // 数据
  reject: function(err){}, // 异常
  timeout: 30000,
  hasCookie: true // 是否携带cookie
});
  • singleFetch

未添加 任何默认 options

// web
import singleFetch from '@rayb/ray-fetch/lib/singleFetch';

// DELETE GET HEAD OPTIONS POST PUT

// single use
singleFetch(url).then(d => console.log(d));
// 处理 success 和 error
singleFetch(url).then(d => {
  // success
  if (d.code>= 200 && d.code < 300>){
    // do success
  } else {
    // do error
  }
});

// 使用
singleFetch(url, {
  method: 'POST',
  headers: headers, // 可选
  body: JSON.stringify(data), // 数据
  reject: function(err){}, // 异常
  timeout: 30000,
  hasCookie: true // 是否携带cookie
});

// 使用自定义 promise 处理 error
function payload(data){
  return new Promise((resolve, reject) => {
    if (data && data.status === 200) {
      resolve(data.result);
    } else {
      if (data && data.message) {
        reject(data.message);
      } else {
        reject(data);
      }
    }
  });
}

singleFetch(url, {
  method: 'POST',
  headers: headers, // 可选
  body: JSON.stringify(data), // 数据
  timeout: 30000,
  hasCookie: true // 是否携带cookie
}).then(payload).then(d => {
  // do success
}, err => {
  // do error
});

check

import { checkStatus, checkJson, checkBlob, checkText, timeoutFetch } from '@rayb/ray-fetch';
// or
// import { checkStatus, checkJson, checkBlob, checkText, timeoutFetch } from '@rayb/ray-fetch/lib/_check';

API

props

nametypedefaultdescription
optsobject-请求参数

rayRequest opts

nametypedefaultdescription
rejectfunction() => {}请求失败时回调
hasCookiebooleanundefined是否携带cookie
isFormDatabooleanundefined是否是formdata,如果是formdata时,body中的数据将不进行string化,此时需要自行修改headers中的 Content-Typeapplication/x-www-form-urlencoded;charset=utf-8、multipart/form-data),formdata使用MIME参考手册
headersobject{ Accept: 'application/json','Content-Type': 'application/json; charset=utf-8','X-Api-Key': Store.getCookieByName('X-Api-Key'),'X-Access-Token': ls.read('X-Access-Token'),}请求headers
methodstring: DELETE、GET、HEAD、OPTIONS、POST、PUTGET请求方式
timeoutnumber30000请求超时,单位 毫秒, 默认 30000毫秒
noApiKeybooleanfalse是否禁用自定添加 X-Api-KeyX-Access-Token headers

注意,当 isFormData=truebody is FormData 时,默认给 headers 添加 application/x-www-form-urlencoded; charset=UTF-8。由于部分场景存在 boundary 问题,取消默认添加

commonRequest

去除 storage 强依赖,用以适配移动端

fetchEventSource

添加 EventSource 支持

import { fetchEventSource, fes } from '@rayb/ray-fetch/lib/fetchEventSource';

fes({
  url,
  method: 'POST',
  headers,
  body,
  onmessage: (evt) => {},
  onclose: (evt) => {}
});


const controller = new AbortController();
const { signal } = controller;

fetchEventSource(url, {
  signal,
  method,
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({}),
  onmessage,
  onclose
});

注意

使用 rayrequest 进行上传文件时,如果 headers 中的 Content-Type 不支持,需要自行修改。如:

// FormData 模式下,默认不设置 `Content-Type`
headers={
  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}

如果其它 POST|PUT|DELETE 请求,无需默认处理 body,此时,可设置 isFormData=true 将不进行 JSON.stringify 处理,headers 中需要自行处理 'Content-Type'

License

MIT

changelog

  • 20230829 v3.0.0 change to @rayb/ray-fetch and add EventSource
  • 20210319 v2.0.2 update timeout 30000
3.0.0

9 months ago

2.1.0

1 year ago

2.0.4

1 year ago

2.0.3

1 year ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago