Skip to content

Commit

Permalink
feat: support promised request interceptor (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
clock157 authored Jul 10, 2019
1 parent 194e5fa commit aaf0bde
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 17 deletions.
50 changes: 33 additions & 17 deletions src/lib/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,40 @@ export const responseInterceptors = [];
function fetch(url, options = {}) {
if (typeof url !== 'string') throw new Error('url MUST be a string');

// 执行 request 的拦截器
requestInterceptors.concat([defaultInterceptor]).forEach(handler => {
const ret = handler(url, options);
url = ret.url || url;
options = ret.options || options;
const combinedRequestInterceptors = requestInterceptors.concat([defaultInterceptor]);

return new Promise(resolve => {
// 执行 request 的拦截器, 处理完以后再去请求
// 使用 async/await 可以使代码更简洁, 但会 引入 regenerator-runtime 导致体积增加一倍, 所以用 promise
combinedRequestInterceptors
.reduce(
(promise, handler) =>
promise.then(ret => {
if (ret) {
url = ret.url || url;
options = ret.options || options;
}
return handler(url, options);
}),
Promise.resolve()
)
.then(ret => {
url = ret.url || url;
options = ret.options || options;

// 将 method 改为大写
options.method = options.method ? options.method.toUpperCase() : 'GET';

// 请求数据
let response = window.fetch(url, options);
// 执行 response 的拦截器
responseInterceptors.forEach(handler => {
response = response.then(res => handler(res, options));
});

resolve(response);
});
});

// 将 method 改为大写
options.method = options.method ? options.method.toUpperCase() : 'GET';

// 请求数据
let response = window.fetch(url, options);
// 执行 response 的拦截器
responseInterceptors.forEach(handler => {
response = response.then(res => handler(res, options));
});

return response;
}

// 支持拦截器,参考 axios 库的写法: https://github.com/axios/axios#interceptors
Expand Down
27 changes: 27 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,33 @@ describe('test fetch lib:', () => {
expect(data.foo).toBe('foo');
});

// 使用上边修改数据的用例, 测试 promise 化的 interceptors
it('test promise interceptors', async () => {
server.post('/test/promiseInterceptors', (req, res) => {
writeData(req.body, res);
});

request.interceptors.request.use((url, options) => {
return new Promise(resolve => {
setTimeout(() => {
if (options.method.toLowerCase() === 'post') {
options.data = {
...options.data,
foo: 'foo',
};
}
resolve({ url, options });
}, 1000);
});
});

const data = await request(prefix('/test/promiseInterceptors'), {
method: 'post',
data: { bar: 'bar' },
});
expect(data.foo).toBe('foo');
});

afterAll(() => {
server.close();
});
Expand Down

0 comments on commit aaf0bde

Please sign in to comment.