All files / src/utils convertEasyFetchResponse.ts

78.78% Statements 26/33
50% Branches 1/2
100% Functions 1/1
78.78% Lines 26/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 381x     1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   14x 14x 14x   14x 14x               14x  
import { RESPONSE_BODY_UNDEFINED_MESSAGE } from '../constant';
import { EasyFetchResponse } from '../types/easyFetch.type';
 
export const convertEasyFetchResponse = async <T>(
  res: Response,
  reqConfig: RequestInit
): Promise<EasyFetchResponse<T> | EasyFetchResponse<undefined>> => {
  const responseWithoutBody: Omit<EasyFetchResponse<T>, 'body'> = {
    headers: res.headers,
    ok: res.ok,
    redirected: res.redirected,
    status: res.status,
    statusText: res.statusText,
    type: res.type,
    url: res.url,
    config: [
      res.url,
      {
        ...reqConfig,
      },
    ],
  };
 
  try {
    const body = (await res.json()) as T;
    const response = { ...responseWithoutBody, body };
 
    return response;
  } catch (err) {
    if ((err as Error).message === RESPONSE_BODY_UNDEFINED_MESSAGE) {
      const response = { ...responseWithoutBody, body: undefined };
      return response;
    } else {
      throw err;
    }
  }
};