Skip to content

Commit

Permalink
perf(middlewares): merge fetcher and payloadConsumer (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
fanhaoyuan committed Jul 20, 2022
1 parent fd07bbf commit a4a5005
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 58 deletions.
4 changes: 2 additions & 2 deletions packages/fatcher/src/fatcher.ts
@@ -1,6 +1,6 @@
import { RequestOptions, ResponseResult } from './interfaces';
import { defaultOptions, mergeOptions } from './options';
import { fetcher, registerMiddlewares, composeMiddlewares, payloadConsumer } from './middlewares';
import { fetcher, registerMiddlewares, composeMiddlewares } from './middlewares';
import { createContext } from './context';
import { canActivate } from './helpers';

Expand All @@ -12,7 +12,7 @@ export async function fatcher<T = any>(inlineOptions: RequestOptions = {}): Prom

const { middlewares: customMiddlewares = [], ...rest } = options;

const registeredMiddlewares = registerMiddlewares([...customMiddlewares, payloadConsumer, fetcher]);
const registeredMiddlewares = registerMiddlewares([...customMiddlewares, fetcher]);

const useMiddlewares = composeMiddlewares(registeredMiddlewares);

Expand Down
34 changes: 32 additions & 2 deletions packages/fatcher/src/middlewares/fetcher.ts
Expand Up @@ -7,13 +7,43 @@ import { FatcherError } from '../errors';
*/
export function fetcher(): Middleware {
return {
name: 'fatcher-middleware-http-fetcher',
name: 'fatcher-middleware-fetch',
async use(context) {
const { url = '', requestHeaders: headers, ...rest } = context;
// eslint-disable-next-line prefer-const
let { url = '', requestHeaders: headers, payload, method = 'GET', body, params, ...rest } = context;

const contentType = headers.get('content-type');

/**
* If Request Method is `GET` or `HEAD`.
*
* Will ignore headers['Content-Type'].
*
* payload will transform into search params.
*/
if (['GET', 'HEAD'].includes(method)) {
params = Object.assign({}, params, body);
body = null;
} else if (payload && contentType) {
if (contentType.includes('application/json')) {
body = JSON.stringify(payload);
}

if (contentType.includes('application/x-www-form-urlencoded')) {
body = new URLSearchParams(payload);
}
}

if (Object.keys(params!).length) {
// Recessive call `toString()` in URLSearchParams
url = `${url}?${new URLSearchParams(params)}`;
}

const response = await fetch(url, {
...rest,
headers,
body,
method,
});

const { status, statusText, ok, headers: responseHeaders } = response;
Expand Down
1 change: 0 additions & 1 deletion packages/fatcher/src/middlewares/index.ts
@@ -1,4 +1,3 @@
export * from './composeMiddlewares';
export * from './fetcher';
export * from './payloadConsumer';
export * from './registerMiddlewares';
53 changes: 0 additions & 53 deletions packages/fatcher/src/middlewares/payloadConsumer.ts

This file was deleted.

0 comments on commit a4a5005

Please sign in to comment.