Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

配置request.interceptors.response.use后,errorHandler失效 #53

Open
wants to merge 107 commits into
base: use/umi-lint
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
107 commits
Select commit Hold shift + click to select a range
a056cc1
doc: add doc vs axios and english readme.
clock157 Feb 16, 2019
3a43d65
refactor: use umi-plugin-library to bundle
clock157 Feb 16, 2019
032ed6e
refactor: use umi-plugin-library to bundle (#22)
sorrycc Feb 17, 2019
c3cc27a
feat: use umi-lint
clock157 Feb 23, 2019
8f22cf4
fix error type
yesmeck Feb 27, 2019
cdd12e1
Merge pull request #26 from umijs/fix-error-type
clock157 Feb 27, 2019
3346cd3
Merge pull request #21 from umijs/doc/vs_axios
sorrycc Mar 14, 2019
df647e9
Update defaultInterceptor.js
saturnism Mar 25, 2019
b36dd7d
Merge pull request #32 from saturnism/http-patch
clock157 Mar 25, 2019
b7ddc5f
publish
clock157 Mar 25, 2019
fba794e
add credentials desc.
zven21 Apr 1, 2019
66caba3
Update index.d.ts
xiaohuoni Apr 2, 2019
683065f
Merge pull request #38 from umijs/xiaohuoni-patch-1
xiaohuoni Apr 2, 2019
362f8f1
Merge pull request #37 from zven21/feature/add-credentials-desc
clock157 Apr 2, 2019
e3c9f3c
fix: index.d.ts 缺少 patch 方法定义
handycode Apr 10, 2019
7c4f882
Merge pull request #42 from handycode/master
clock157 Apr 11, 2019
14e12e4
publish 1.0.6
clock157 Apr 11, 2019
d08636a
feat: Send data using delete
xchunzhao Apr 17, 2019
c85c29d
test: Add delete method test case
xchunzhao Apr 18, 2019
e9e4332
Merge pull request #45 from xchunzhao/master
clock157 Apr 20, 2019
8a11497
Merge branch 'master' into use/umi-lint-new
clock157 Apr 20, 2019
7c0e92b
refactor: use umi-lint format code
clock157 Apr 20, 2019
c10a9b5
Merge pull request #24 from umijs/use/umi-lint-new
clock157 Apr 24, 2019
0cc6caf
publish: 1.0.7
clock157 Apr 24, 2019
2c6e690
type support async
chenshuai2144 May 7, 2019
8e674fc
Merge pull request #51 from umijs/fix-type
chenshuai2144 May 7, 2019
7f72580
chore: update README.md
sorrycc May 8, 2019
a4b5caf
Update README.md
clock157 May 15, 2019
9382bed
Update README_zh-CN.md
clock157 May 15, 2019
b0cceb6
chore: use np for publish
sorrycc Jun 12, 2019
75ffc14
v1.0.8
sorrycc Jun 12, 2019
6709011
doc: upload file example code (#54)
clock157 Jul 3, 2019
194e5fa
refactor: revise response data processing (#55)
Jul 7, 2019
aaf0bde
feat: support promised request interceptor (#57)
clock157 Jul 10, 2019
832118f
publish: 1.1.0
clock157 Jul 10, 2019
1f77c34
feat: support middleware
chenjsh36 Jul 16, 2019
74fb55b
test: add test case to code coverage rate
Jul 19, 2019
c68a407
feat: support middleware (#59)
sorrycc Jul 19, 2019
a841cab
Update README.md (#58)
ycjcl868 Jul 19, 2019
b0dadc2
1.1.1
Jul 19, 2019
789e8a7
Add missing properties `credentials` in interface `RequestOptionsInit…
ForeverArt Jul 22, 2019
ff9f83e
fix: support fetch (#61)
chenjsh36 Jul 31, 2019
5aeef72
1.2.0
chenjsh36 Jul 31, 2019
db38fdb
fix: remove properties in interface (#62)
chenjsh36 Jul 31, 2019
39d0557
1.2.1
chenjsh36 Jul 31, 2019
d1cb5c0
fix: update properties 'next' in interface 'OnionMiddleware' (#63)
chenjsh36 Aug 3, 2019
010a56a
1.2.2
chenjsh36 Aug 5, 2019
aec901b
Feat/support cancel request (#64)
chenjsh36 Aug 22, 2019
9ac6750
1.2.3
chenjsh36 Aug 22, 2019
4d12e47
Feat/support node http (#65)
chenjsh36 Aug 29, 2019
827b7d7
1.2.4
chenjsh36 Aug 29, 2019
3811530
feat: middleware support global type and instance type (#66)
chenjsh36 Sep 9, 2019
d01dada
1.2.5
chenjsh36 Sep 9, 2019
a95c802
feat: add request and response in error object; update readme doc (#67)
chenjsh36 Sep 23, 2019
3ef4c73
1.2.6
chenjsh36 Sep 23, 2019
e21a3c7
Fix/credentials default value (#68)
chenjsh36 Oct 10, 2019
86c1b7d
1.2.7
chenjsh36 Oct 10, 2019
56daaea
Update README.md
chenjsh36 Oct 10, 2019
8ebf824
fix: params serialize fail when keyvalue is 'null'. (#70)
chenjsh36 Oct 13, 2019
af4c10c
1.2.8
chenjsh36 Oct 13, 2019
2853dc8
Update utils.js (#69)
ourfeel Oct 16, 2019
84b2955
feat: add instance Interceptors (#71)
zouxiaomingya Nov 9, 2019
051f4d6
update:replace symbol (#72)
Nov 9, 2019
9f5d40e
1.2.9
chenjsh36 Nov 9, 2019
2bc3113
Feat/qs cache (#74)
chenjsh36 Nov 20, 2019
3a1e787
1.2.10
chenjsh36 Nov 20, 2019
e0bb007
fix: qs stringify problem (#75)
chenjsh36 Nov 21, 2019
eb7ed77
1.2.11
chenjsh36 Nov 21, 2019
b9b76a2
feat: provide 'extendOptions()' (#80)
chenjsh36 Dec 5, 2019
8131592
1.2.12
chenjsh36 Dec 5, 2019
8b38e1c
1.2.13
chenjsh36 Dec 9, 2019
b519983
fix: 'Cannot clone a disturbed Response' bug in ios 10 (#82)
chenjsh36 Dec 9, 2019
d6a064e
fix: multiple clone response on ios.10 will throw error (#83)
chenjsh36 Dec 9, 2019
6374e47
1.2.14
chenjsh36 Dec 9, 2019
93377bc
fix: update type of interceptors (#89)
DiamondYuan Dec 12, 2019
b52f2ea
1.2.15
chenjsh36 Dec 12, 2019
fb0137d
Fix/catch reject from fetch (#95)
chenjsh36 Dec 24, 2019
5db96ac
1.2.16
chenjsh36 Dec 24, 2019
ed430f8
fix: extendOptions fail on method (#97)
chenjsh36 Dec 26, 2019
2fe1f9b
1.2.17
chenjsh36 Dec 26, 2019
e825313
feat: add defaultInstance option for middlewares (#102)
chenjsh36 Jan 20, 2020
192b5a5
1.2.18
chenjsh36 Jan 20, 2020
75bed1b
fix: overwrite the error object (#108)
chenjsh36 Feb 18, 2020
d9eb129
1.2.19
chenjsh36 Feb 18, 2020
4522b07
feat: 添加abort controller 取消请求 (#90)
suxin2017 May 21, 2020
6a424cf
Feat: add abort request polyfill and update types (#148)
chenjsh36 May 22, 2020
a7db8c0
1.3.0
chenjsh36 May 22, 2020
60917c1
fix: add AbortController polyfill (#150)
chenjsh36 May 25, 2020
0232e30
1.3.2
chenjsh36 May 25, 2020
eaca25e
1.3.4
chenjsh36 Jun 17, 2020
5882668
[typo] fix typo (#155)
Wzb3422 Sep 14, 2020
7d2f452
fix: 修复 Oinon 拼写错误 (#153)
xiabaiyang Sep 14, 2020
6773ef1
Fix typo (#151)
AhmadMayo Sep 14, 2020
318ba2d
feat: store origin request url in options (#244)
ttys026 May 19, 2021
b8eb5f3
1.3.6
ttys026 May 25, 2021
0f65468
chore: switch build tool to father (#248)
focus7eleven May 25, 2021
6fe176a
1.3.7
ttys026 May 25, 2021
ce6c73f
fix: missing package main entry (#250)
ttys026 May 25, 2021
f86c873
1.3.8
ttys026 May 25, 2021
17867b5
chore: remove abort controller polyfill (#251)
ttys026 May 25, 2021
9146ebc
1.3.9
ttys026 May 26, 2021
d0f3a45
Merge branch 'master' of https://github.com/umijs/umi-request
ttys026 May 26, 2021
99c3281
feature: 增加 timeoutMessage 配置 (#267)
WynterDing Sep 14, 2021
7ac65e0
v1.4.0
chenshuai2144 Sep 14, 2021
7856e98
修改文档上传文件示例问题 (#265)
jiangkaifree Sep 14, 2021
48a074f
Update README_zh-CN.md (#256)
wood3n Sep 14, 2021
50197be
Update cancel.js (#234)
weishaodaren Sep 14, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Feat/qs cache (#74)
* feat: use 'qs' module instead of 'query-string' to dealwith pack problem

* feat: add 'validateCache' for cache strategy
  • Loading branch information
chenjsh36 authored Nov 20, 2019
commit 2bc31139197cdb64fa066ad24eed3b029900e4b8
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ More umi-request cases can see [antd-pro](https://github.com/umijs/ant-design-pr
| suffix | suffix, such as some scenes api need to be unified .json | string | -- |
| credentials | fetch request with cookies | string | -- | credentials: 'same-origin' |
| useCache | Whether to use caching (only support browser environment) | boolean | -- | false |
| validateCache | cache strategy function | (url, options) => boolean | -- | only get request to cache |
| ttl | Cache duration, 0 is not expired | number | -- | 60000 |
| maxCache | Maximum number of caches | number | -- | 0(Infinity) |
| requestType | post request data type | string | json , form | json |
Expand Down Expand Up @@ -299,7 +300,7 @@ The other parameters of fetch are valid. See [fetch documentation](https://githu
credentials: 'same-origin', // default

// ’useCache‘ The GET request would be cache in ttl milliseconds when 'useCache' is true.
// The cache key would be 'url + params'.
// The cache key would be 'url + params + method'.
useCache: false, // default

// 'ttl' cache duration(milliseconds),0 is infinity
Expand All @@ -308,6 +309,11 @@ The other parameters of fetch are valid. See [fetch documentation](https://githu
// 'maxCache' are the max number of requests to be cached, 0 means infinity.
maxCache: 0,

// According to http protocal, request of GET used to get data from server, it's necessary to cache response data when server data update not frequently. We provide 'validateCache'
// for some cases that need to cache data with other method reqeust.
validateCache: (url, options) => { return options.method.toLowerCase() === 'get' },


// 'requestType' umi-request will add headers and body according to the 'requestType' when the type of data is object or array.
// 1. requestType === 'json' :(default )
// options.headers = {
Expand Down
11 changes: 8 additions & 3 deletions README_zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,9 @@ umi-request 可以进行一层简单封装后再使用, 可参考 [antd-pro](htt
| timeout | 超时时长, 默认毫秒, 写操作慎用 | number | -- | -- |
| prefix | 前缀, 一般用于覆盖统一设置的prefix | string | -- | -- |
| suffix | 后缀, 比如某些场景 api 需要统一加 .json | string | -- | -- |
| credentials | fetch 请求包含 cookies 信息 | object | -- | credentials: 'same-origin' |
| credentials | fetch 请求包含 cookies 信息 | string | -- | credentials: 'same-origin' |
| useCache | 是否使用缓存(仅支持浏览器客户端) | boolean | -- | false |
| validateCache | 缓存策略函数 | (url, options) => boolean | -- | 默认 get 请求做缓存 |
| ttl | 缓存时长, 0 为不过期 | number | -- | 60000 |
| maxCache | 最大缓存数 | number | -- | 无限 |
| requestType | post请求时数据类型 | string | json , form | json |
Expand Down Expand Up @@ -299,7 +300,7 @@ fetch原其他参数有效, 详见[fetch文档](https://github.github.io/fetch/)
// 要改为确保浏览器不在请求中包含凭据,请使用credentials: 'omit'
credentials: 'same-origin', // default

// ’useCache‘ 是否使用缓存,当值为 true 时,GET 请求在 ttl 毫秒内将被缓存,缓存策略唯一 key 为 url + params 组合
// ’useCache‘ 是否使用缓存,当值为 true 时,GET 请求在 ttl 毫秒内将被缓存,缓存策略唯一 key 为 url + params + method 组合
useCache: false, // default

// ’ttl‘ 缓存时长(毫秒), 0 为不过期
Expand All @@ -308,6 +309,9 @@ fetch原其他参数有效, 详见[fetch文档](https://github.github.io/fetch/)
// 'maxCache' 最大缓存数, 0 为无限制
maxCache: 0,

// 根据协议规范, GET 请求用于获取、查询服务端数据,在数据更新频率不频繁的情况下做必要的缓存能减少服务端的压力,因为缓存策略是默认对 GET 请求做缓存,但对于一些特殊场景需要缓存其他类型请求的响应数据时,我们提供 validateCache 供用户自定义何时需要进行缓存, key 依旧为 url + params + method
validateCache: (url, options) => { return options.method.toLowerCase() === 'get' },

// 'requestType' 当 data 为对象或者数组时, umi-request 会根据 requestType 动态添加 headers 和设置 body(可传入 headers 覆盖 Accept 和 Content-Type 头部属性):
// 1. requestType === 'json' 时, (默认为 json )
// options.headers = {
Expand Down Expand Up @@ -452,7 +456,8 @@ request('/api/v1/xxx')


## 中间件
类 koa 的洋葱机制,让开发者优雅地做请求前后的增强处理,支持创建实例、全局、内核中间件。

类 koa 的洋葱机制,让开发者优雅地做请求前后的增强处理,支持创建实例、全局、内核中间件。

**实例中间件(默认)** :request.use(fn) 不同实例创建的中间件相互独立不影响;

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
},
"dependencies": {
"isomorphic-fetch": "^2.2.1",
"query-string": "^6.0.0"
"qs": "^6.9.1"
},
"files": [
"dist/",
Expand Down
30 changes: 25 additions & 5 deletions src/middleware/fetch.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,33 @@
import 'isomorphic-fetch';
import { timeout2Throw, cancel2Throw, getEnv } from '../utils';

// 是否已经警告过
let warnedCoreType = false;

// 默认缓存判断,开放缓存判断给非 get 请求使用
function __defaultValidateCache(url, options) {
const { method = 'get' } = options;
return method.toLowerCase() === 'get';
}

export default function fetchMiddleware(ctx, next) {
if (!ctx) return next();
const { req: { options = {}, url = '' } = {}, cache, responseInterceptors } = ctx;
const { timeout = 0, __umiRequestCoreType__ = 'normal', useCache = false, method = 'get', params, ttl } = options;
const {
timeout = 0,
__umiRequestCoreType__ = 'normal',
useCache = false,
method = 'get',
params,
ttl,
validateCache = __defaultValidateCache,
} = options;

if (__umiRequestCoreType__ !== 'normal') {
if (process && process.env && process.env.NODE_ENV === 'development') {
if (process && process.env && process.env.NODE_ENV === 'development' && warnedCoreType === false) {
warnedCoreType = true;
console.warn(
'__umiRequestCoreType__ is a internal property that use in umi-request, change its value would affect the behavior of request! It only use when you want to extend the request core.'
'__umiRequestCoreType__ is a internal property that use in umi-request, change its value would affect the behavior of request! It only use when you want to extend or use request core.'
);
}
return next();
Expand All @@ -23,11 +41,13 @@ export default function fetchMiddleware(ctx, next) {

// 从缓存池检查是否有缓存数据
const isBrowser = getEnv() === 'BROWSER';
const needCache = method.toLowerCase() === 'get' && useCache && isBrowser;
const needCache = validateCache(url, options) && useCache && isBrowser;
console.log('needCache:', needCache, url);
if (needCache) {
let responseCache = cache.get({
url,
params,
method,
});
if (responseCache) {
responseCache = responseCache.clone();
Expand Down Expand Up @@ -56,7 +76,7 @@ export default function fetchMiddleware(ctx, next) {
if (res.status === 200) {
const copy = res.clone();
copy.useCache = true;
cache.set({ url, params }, copy, ttl);
cache.set({ url, params, method }, copy, ttl);
}
}

Expand Down
7 changes: 4 additions & 3 deletions src/middleware/simpleGet.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { stringify } from 'query-string';
import { stringify } from 'qs';
import { isArray, isURLSearchParams, forEach2ObjArr, isObject, isDate } from '../utils';

export function paramsSerialize(params, paramsSerializer) {
Expand All @@ -20,7 +20,8 @@ export function paramsSerialize(params, paramsSerializer) {
jsonStringifiedParams.push(isObject(item) ? JSON.stringify(item) : item);
}
});
serializedParams = stringify(jsonStringifiedParams);
// a: [1,2,3] => a=1&a=2&a=3
serializedParams = stringify(jsonStringifiedParams, { arrayFormat: 'repeat', strictNullHandling: true });
} else {
jsonStringifiedParams = {};
forEach2ObjArr(params, function(value, key) {
Expand All @@ -36,7 +37,7 @@ export function paramsSerialize(params, paramsSerializer) {
}
jsonStringifiedParams[key] = jsonStringifiedValue;
});
const tmp = stringify(jsonStringifiedParams);
const tmp = stringify(jsonStringifiedParams, { arrayFormat: 'repeat', strictNullHandling: true });
serializedParams = tmp;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/simplePost.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { stringify } from 'query-string';
import { stringify } from 'qs';

// 对请求参数做处理,实现 query 简化、 post 简化
export default function simplePostMiddleware(ctx, next) {
Expand Down
4 changes: 2 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* 实现一个简单的Map cache, 稍后可以挪到 utils中, 提供session local map三种前端cache方式.
* 1. 可直接存储对象 2. 内存无5M限制 3.缺点是刷新就没了, 看反馈后期完善.
*/
import { parse } from 'query-string';
import { parse } from 'qs';

export class MapCache {
constructor(options) {
Expand Down Expand Up @@ -172,7 +172,7 @@ export function forEach2ObjArr(target, callback) {

export function getParamObject(val) {
if (isURLSearchParams(val)) {
return parse(val.toString());
return parse(val.toString(), { strictNullHandling: true });
}
if (typeof val === 'string') {
return [val];
Expand Down
2 changes: 1 addition & 1 deletion test/fetch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ describe('timeout', () => {
await fetch('/api/test', { __umiRequestCoreType__: 'other' });
expect(console.warn.mock.calls.length).toBe(1);
expect(console.warn.mock.calls[0][0]).toBe(
'__umiRequestCoreType__ is a internal property that use in umi-request, change its value would affect the behavior of request! It only use when you want to extend the request core.'
'__umiRequestCoreType__ is a internal property that use in umi-request, change its value would affect the behavior of request! It only use when you want to extend or use request core.'
);
process.env.NODE_ENV = 'test';
done();
Expand Down
31 changes: 31 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,37 @@ describe('test fetch:', () => {
expect(response.data.defaultParams).toBe('true');
}, 10000);

it('test validate cache', async () => {
server.post('/test/validate/cache', (req, res) => {
writeData(req.query, res);
});
server.get('/test/validate/cache', (req, res) => {
writeData(req.query, res);
});
const extendRequest = extend({
maxCache: 2,
prefix: server.url,
headers: { Connection: 'keep-alive' },
params: { defaultParams: true },
validateCache: (url, options) => {
const { method = 'get' } = options;
if (method.toLowerCase() === 'post') {
return true;
}
return false;
},
getResponse: true,
useCache: true,
});
let response = await extendRequest('/test/validate/cache', { method: 'post' });
response = await extendRequest('/test/validate/cache', { method: 'post' });

expect(response.response.useCache).toBe(true);

response = await extendRequest('/test/validate/cache', { method: 'get' });
expect(response.response.useCache).toBe(false);
});

it('test extends', async () => {
server.get('/test/method', (req, res) => {
writeData({ method: req.method }, res);
Expand Down
22 changes: 22 additions & 0 deletions test/interceptor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,4 +201,26 @@ describe('interceptor', () => {
expect(data.promiseFoo).toBe('promiseFoo');
done();
});

// reject in interceptor
it('throw error in response interceptor', async done => {
server.post('/test/reject/interceptor', (req, res) => {
writeData(req.body, res);
});

request.interceptors.response.use((response, options) => {
const { status, url } = response;
console.log('status', status, url);
if (status === 200 && url.indexOf('/test/reject/interceptor')) {
throw Error('reject when response is 200 status');
}
});

try {
const data = await request(prefix('/test/reject/interceptor'), { method: 'post' });
} catch (e) {
expect(e.message).toBe('reject when response is 200 status');
done();
}
});
});
1 change: 1 addition & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export interface RequestOptionsInit extends RequestInit {
parseResponse?: boolean;
cancelToken?: CancelToken;
getResponse?: boolean;
validateCache?: (url: string, options: RequestOptionsInit) => boolean;
}

export interface RequestOptionsWithoutResponse extends RequestOptionsInit {
Expand Down