1 Star 0 Fork 1

JA+ / ja-fetch

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

ja-fetch

A simple fetch wrapper, refer to some axios API. (parsed:5KB)

  • Optimize fetch: method "get", set params to transfer parameters.
  • Optimize fetch: Auto JSON.stringify post body.
  • default return response.json(). (Set responseType to change)
  • support interceptor.
  • support cancel request interceptor preset.

RequestInit extends Fetch API(MDN)

TODO

  • getPendingPromiseList
  • support Request obj

API

import http from 'ja-fetch';
http.get(url[, init]).then(data => {});
let service = http.create([init]);
service.interceptors.request.use(onFulfilled[, onRejected]);
service.interceptors.response.use(onFulfilled[, onRejected]);
service.interceptors.use(preset);
service.get(url[, init]).then(data => {});

Usage Demo

Basic usage

import http from "ja-fetch";
http.request(url, {
    method: 'GET',// POST PUT DELETE
    params: { type: "aa", data: "ddd" },
    mode: "cors",
})
// get
http.get(url, {
    params: { type: "aa", data: "ddd" },
    mode: "cors",
    // credentials: 'include',
    // responseType: 'text' | 'arraybuffer' | 'blob' | 'json' 
    // responseType: 'response' // return raw fetch Response Object
})
// post
http.post(url, {
    params: { id: "11" }, // Concatenated after the URL
    body: { type: "json" },
})
// formData
let formData = new FormData();
    formData.append("type", "formData");

http.post(url, {
    params: { id: "11" },
    body: formData,
})
// put 
http.put(url, {
    params: { id: "pp" },
    body: { type: "put" },
})
// delete
http.del(url, {
    params: { id: "del" },
    body: { type: "delete" },
})

Interceptor demo

import http from "ja-fetch";
const service = http.create({
  mode: "cors",
  baseURL: 'http://xxx.cn',
  // rawBody: true, // Not auto JSON.stringify(body)
  // credentials: 'include' // cookie
  // responseType: 'text' | 'arraybuffer' | 'blob' | 'json' | 'response'
});
service.interceptors.request.use(
    (url, init) => {
        init.headers.userToken = "11111";
        return init; // support return Promise
    },
    (err, {url, init}) => {
        console.log("request interceptor err:", err);
        return Promise.reject(err);
    }
);
service.interceptors.response.use(
    (data, { url, init }, response) => {
        if (data.code === 1) {
            return data; // You MUST return data;
        } else {
            return Promise.reject("response.data.code is " + data.code);
        }
    },
    (err, { url, init }, response) => {
        console.log("response interceptor err:", err);
        return Promise.reject(err); // Promise.resolve('data')
    }
);

service.get('/getData',{ params: { a: 1 } }).then(data => {...})

// use other interceptor
service.interceptors.use({
  install(interceptor){
    interceptor.request.use(/*... */)
    interceptor.response.use(/*... */)
  }
})

Cancel Request Demo

Use AbortController(MDN) to cancel request (Chrome >= 66)

Basic

import http from 'ja-fetch';
const fetchBtn = document.querySelector('#fetch'); // <button></button>
let controller; // save request abortController

fetchBtn.addEventListener('click', () => {
    if (controller) controller.abort(); // abort a request

    controller = new AbortController();
    http.get('http://localhost:8080/timeoutTestData', { 
        params: { timeout: 4000 }, 
        signal: controller.signal
    }).then(data => {
        console.log('data', data)
    }).catch(err => {
        console.warn('fetch canceled', err);
    }).finally(() => {
      controller = null
    });
});

In interceptors

  import http from "ja-fetch";
  let Service = http.create();
  let cacheArr = [];
  Service.interceptors.request.use((url, init) => {
    cacheArr.forEach((item) => {
      // abort same url
      if (item.url === url) {
        item.controller.abort();
        item.canceled = true;
      }
    });
    let abController = new AbortController();
    init.signal = abController.signal;
    cacheArr.push({
      url,
      controller: abController,
      cancel: false,
    });
  });
  Service.interceptors.response.use((data, { url, init }) => {
    cacheArr = cacheArr.filter((item) => !item.canceled); // clean canceled cache
  });

Interceptor Presets

function describe
commonCancelRequest cancel last same request
commonThrottleRequest wait last same request return
commonParallelRequest parallel request
commonTimeoutRequest(option:{ms:number}) request cancel when timeout

Use Cancel Request Preset

  import http from 'ja-fetch'
  import { commonCancelRequest, commonThrottleRequest, commonParallelRequest, commonTimeoutRequest } from 'ja-fetch/preset/interceptors.js'
  let ServiceAB = http.create()
  ServiceAB.interceptors.use(commonCancelRequest()) // url === url && method === method
  ServiceAB.get(url, { params, notCancel: true })  // let a request not be canceled

or custom cancel rule

  ServiceAB.interceptors.use(
    commonCancelRequest((nowRequest, storedRequest) => {
    /**
     * @typedef storedRequest / nowRequest
     * @property {string} url
     * @property {RequestInit} init 
     */
      return storedRequest.url === nowRequest.url
    }, {
        notCancelKey: 'notCancel',
        gcCacheArrNum: 20, // 数组大于该值,对数组中的元素进行回收
    }),

    // let a request not be canceled
    ServiceAB.get(url, {params, notCancel: true})
  )

About project

  • node > 16
MIT License Copyright (c) 2022 JA+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

使用Fetch API 参考 axios API的简易封装。min.js约3kb。 展开 收起
JavaScript 等 3 种语言
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
JavaScript
1
https://gitee.com/japlus/ja-fetch.git
git@gitee.com:japlus/ja-fetch.git
japlus
ja-fetch
ja-fetch
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891