All files / src/utils createPrototypeAPIMethod.ts

100% Statements 33/33
100% Branches 8/8
100% Functions 2/2
100% Lines 33/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 441x           60x 60x 60x 60x 60x 60x   60x 36x   4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 60x 24x   6x 6x 6x 6x 6x 6x 6x 6x 24x 60x   1x  
import { METHOD_WITH_BODY } from '../constant';
import EasyFetch from '../EasyFetch';
import { EasyFetchResponse } from '../types/easyFetch.type';
import { MethodType } from '../types/method.type';
import { RequestInitWithNextConfig } from '../types/nextProperty.type';
 
function createPrototypeAPIMethod(method: MethodType) {
  const hasBodyMethod = (
    method: MethodType
  ): method is (typeof METHOD_WITH_BODY)[number] => {
    return METHOD_WITH_BODY.some((m) => m === method);
  };
 
  if (hasBodyMethod(method)) {
    return async function <T>(
      this: EasyFetch,
      url: string | URL,
      reqBody?: object,
      reqConfig?: Omit<RequestInitWithNextConfig, 'method' | 'body'>
    ): Promise<EasyFetchResponse<T>> {
      const mergedRequestConfigWithBody: RequestInitWithNextConfig = {
        ...reqConfig,
        body: reqBody && JSON.stringify(reqBody),
        method: method.toUpperCase(),
      };
 
      return this.request<T>(url, mergedRequestConfigWithBody);
    };
  } else {
    return async function <T>(
      this: EasyFetch,
      url: string | URL,
      reqConfig?: RequestInitWithNextConfig
    ): Promise<EasyFetchResponse<T>> {
      return this.request<T>(url, {
        ...reqConfig,
        method: method.toUpperCase(),
      });
    };
  }
}
 
export default createPrototypeAPIMethod;