cute http
1.0.0
cute 對快取做了優化,同一個url 的get 請求,如果query 參數不變,就優先取快取結果,取不到再去後端要,如果發生變化,會刪除先前的快取結果看,並去後端請求新結果,這樣防止快取過多無用數據
預設使用保證請求執行完畢,才回傳結果,就算有其中一個請求出現錯誤,也不會影響其他請求,當然,此時用戶需要遍歷回傳的結果數據,因為可能其中有一個是錯誤。 用戶也可以設定為發起多個請求時,只要有一個請求錯誤,就全部失敗。
安裝cute-http
npm i cute-http --save
引入
import * as cute from 'cute-http';
const {ONE_ERROR_ABORT_ALL, KEEP_ALL_BEEN_EXECUTED, LOCAL_STORAGE, MEMORY} = cute.const;
localStorage
memory
頂層api,為cute 設定參數
cute setConfig({
retryCount: number,//重试次数
timeout: 1900,//超时时间(毫秒)
debug:true,//打开debug模式
// cacheType: MEMORY, // 默认无,如果开启了缓存,cute只针对get请求做缓存,如需穿透缓存,可以对query参数加随机值,或者调用cute.get时,配置第二个参数{cacheType:null},表示针对这一次调用不读取缓存值
// failStrategy: ONE_ERROR_ABORT_ALL, //不设置的话,cute默认采用KEEP_ALL_BEEN_EXECUTED
})
/**
* 发起多个post请求
* @param {Array<{type:'post', url:string, data:object} | {type:'get', url:string} | {type:'jsonp', url:string} >} items
* @param {{failStrategy?:number, retryCount?:number, callbackParamName?:string, [otherAxiosConfigKey]:any}} extendedAxiosConfig
* otherAxiosConfigKey @see https://github.com/axios/axios
*/
cute.multi(urls, extendedAxiosConfig)
// data 会被自动stringify拼接到url末尾
cute.get(url:string, data:string|object, extendedAxiosConfig:ExtendedAxiosConfig)
cute.multiGet(urls:string[] | {url:string, data:string|object}[], extendedAxiosConfig:ExtendedAxiosConfig)
cute.post(url:string, data:object, extendedAxiosConfig:ExtendedAxiosConfig)
cute.multiPost({url:string, data:object}[], extendedAxiosConfig:ExtendedAxiosConfig)
// data 会被自动stringify拼接到url末尾
cute.jsonp(url:string, data:string|object, extendedAxiosConfig:ExtendedAxiosConfig)
cute.multiJsonp(urls:string[] | {url:string, data:string|object}[], extendedAxiosConfig:ExtendedAxiosConfig)
當然,你也可以註解掉某些程式碼,只看其中一個的效果
const cute = require('../index');
const {ONE_ERROR_ABORT_ALL, KEEP_ALL_BEEN_EXECUTED, MEMORY} = cute.const;
const axios = cute.axios;//这个是axios模块的引用
cute.setConfig({
retryCount: 3,//设置重试次数
timeout: 1900,//设置超时时间
debug: true,
dataVerifyRule: {//设置通用的响应数据校验规则,只支持校验json对象的第一层key的值和类型的校验
data: 'object',
code: 'number',
message: 'string',
},
pathDataVerifyRule:{//对某些请求设置独立的数据校验规则
'/staff/foo':{
reply:'object',
msg:'string',
}
}
cacheType: MEMORY, // 值为 'memory' | 'localStorage' 默认无
failStrategy: KEEP_ALL_BEEN_EXECUTED, //不设置的话,cute默认采用ONE_ERROR_ABORT_ALL
})
const updateBook = 'http://localhost:8888/update-book';
const getBooksByUid = uid => `http://localhost:8888/get-books?uid=${uid}`;
async function main(){
const result1 = await cute.get(getBooksByUid(1));
const books = result.result1;
const result2 = await cute.multiGet([getBooksByUid(1), getBooksByUid(2)]);
const [reply1, reply2] = result2;
const result3 = await cute.post(updateBook, {id:1, name:'zk'});
const updateReply = result.result3;
const result4 = await cute.multiPost([{url:updateBook, body:{id:1, name:'zk'}}, {url:updateBook, body:{id:2, name:'wow'}}]);
const [updateReply1, updateReply2] = result4;
}
更多範例請見/test/test-api.js
運行模擬伺服器
* npm start
執行測試腳本
* npm test