This repository has been archived by the owner on Jul 29, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
RFC: middleware #5
Comments
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
借鉴 Apollo Link, 引入 在 |
恩,我们先列举一下需要处理哪些场景。然后再定:
假设我们对 Request 做处理的场景是:
Response 的处理:
然后,我们再定这个处理函数的入参、出参。我在这个分支了写过一个: |
场景一:log能打印以下这些以及相对时间: 请求前的 yabRequestInit 中间件采取 middleware 方式的代码示例const log = (next) => (yabRequest) => {
const startTime = new Date().getTime();
console.log('yabRequest:', yabRequest);
return next(yabRequest).then(response => {
console.log('raw response:', response);
timeCost(startTime);
// check status
if (response.ok) {
return response.json()
} else {
throw response;
}
}).then(data => {
console.log('data:', data);
timeCost(startTime);
}).catch(e => {
console.error('error:', e);
timeCost(startTime);
});
}
const timeCost = (startTime) => {console.log('time cost:', new Date().getTime() - startTime)};
applyMiddleware(...middleware)(innerFetch)(yabRequest);
innerFetch(yabRequest) {
const { url, ...init } = yabRequest;
return fetch(url, init);
} |
线下讨论之后,一致通过使用类似 Koa 的 middleware API。整理如下: Koa-like APIfetch.use(async (context, next) => {
const startTime = new Date();
await next();
console.info(new Date() - startTime);
}); ContextRequestctx.getYabRequestInit();
ctx.setYabRequestInit();
// ... Response// Raw response
ctx.getResponse(); // response.clone()
ctx.setResponse();
// Consumer
ctx.json();
ctx.text();
ctx.getReader();
// ... Default Middlewares
|
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
看了 @leohxj 总结的各大请求库的 interceptor | middleware | hook,一般用于请求返回值的处理,日志和错误处理等场景。在这里先总结一下:
Axios
使用 interceptor, transform
interceptor 可以设置在 global 和实例上,采用链式调用的顺序依次执行和传递上一个返回的参数。
transformRequest 和 transformResponse 位于最接近 request 的位置,只能处理 data(POST,PUT,...) 和 header。
Before
interceptors.request.use 可以处理和修改请求 config。
transformRequest 可以处理和修改 data,header。
After
interceptors.response.use可以处理和修改 response。
transformRequest 可以做 data,header 的处理和修改
旧的 Hooks 想法
隐含逻辑太多,已放弃
Example
The text was updated successfully, but these errors were encountered: