All files / src rfetch.ts

100% Statements 43/43
96.29% Branches 26/27
100% Functions 9/9
100% Lines 40/40

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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275                                  13x 13x 13x 13x                     1x 1x 1x           1x       1x                         32x           32x     32x 2x 5x 7x   5x   2x 1x   4x 3x   4x           32x 4x 1x 3x 1x 1x         2x 2x             32x     2x           32x       1x 25x   24x     7x           7x   2x                         1x 2x                                                                                                                                                                                                                                                                      
export type RibbonFetchOptions = {
  method?: 'GET' | 'PUT' | 'POST' | 'PATCH' | 'DELETE';
  params?: Record<string, any>;
  body?: any;
  headers?: HeadersInit;
} & Omit<RequestInit, 'body' | 'headers' | 'method'>;
 
export type RibbonFetchBasicOptions = Omit<RibbonFetchOptions, 'method' | 'body'>;
 
export type RibbonFetchBodyOptions = Omit<RibbonFetchOptions, 'method'>;
 
export class RibbonFetchError<R> extends Error {
  public status: number;
  public headers: Headers;
  public content: R;
 
  constructor({ status, content, headers }: { status: number; content: R; headers?: Headers }) {
    super(content?.toString());
    this.status = status;
    this.content = content;
    this.headers = headers ?? new Headers();
  }
}
 
export type RibbonRequestInterceptor = (url: URL, options: RequestInit) => RequestInit | Promise<RequestInit>;
export type RibbonResolveInterceptor = (url: URL, options: RequestInit) => RequestInit | Promise<RequestInit>;
export type RibbonRejectInterceptor = (
  url: URL,
  error: RibbonFetchError<any>
) => RibbonFetchError<any> | Promise<RibbonFetchError<any>>;
 
export enum DelimiterType {
  COMMA,
  DUPLICATE,
}
 
const fetchInterceptors: {
  request: RibbonRequestInterceptor[];
  reject: RibbonRejectInterceptor[];
} = {
  request: [],
  reject: [],
};
let delimiter: DelimiterType = DelimiterType.DUPLICATE;
 
/**
 * A lightweight wrapper around fetch to simplify its usage.
 *
 * @param url The url you wish to fetch.
 * @param options The request options.
 * @returns The typed response or an error containing the `status` and the `content`
 */
export async function rfetch<T = any>(
  url: string | URL,
  { params, body, ...options }: RibbonFetchOptions = {}
): Promise<T> {
  const requestInit: RequestInit = {
    method: 'GET',
    ...options,
  };
 
  // Standardize our url to the `URL` type
  const internalURL = url instanceof URL ? url : new URL(url, url.startsWith('/') ? location.origin : undefined);
 
  // Apply the query params to the url.
  if (params) {
    for (const [key, value] of Object.entries(params)) {
      let values = Array.isArray(value) ? value : [value];
      values = values.filter((value) => ![undefined, null].includes(value));
 
      switch (delimiter) {
        case DelimiterType.COMMA:
          internalURL.searchParams.set(key, values.map((value) => value.toString()).join(','));
          break;
        case DelimiterType.DUPLICATE:
          values.forEach((value) => {
            internalURL.searchParams.append(key, value.toString());
          });
          break;
      }
    }
  }
 
  // Dynamically determine the content-type based upon the data provided to us.
  if (requestInit.method !== 'GET' && body) {
    if (body instanceof FormData) {
      requestInit.body = body;
    } else if (typeof body === 'string') {
      requestInit.body = body;
      requestInit.headers = {
        'Content-Type': 'application/json',
        ...requestInit.headers,
      };
    } else {
      requestInit.body = JSON.stringify(body);
      requestInit.headers = {
        'Content-Type': 'application/json',
        ...requestInit.headers,
      };
    }
  }
 
  const response = await fetch(
    internalURL,
    await fetchInterceptors.request.reduce(
      async (output, interceptor) => await interceptor(internalURL, await output),
      Promise.resolve(requestInit)
    )
  );
 
  // Dynamically determine the content we received and parse it accordingly.
  const content = response.headers.get('Content-Type')?.toLowerCase()?.includes('json')
    ? await response.json()
    : await response.text();
 
  if (response.ok) {
    if (response.status === 204) return undefined as T;
 
    return content;
  }
 
  const error = new RibbonFetchError({
    status: response.status,
    headers: response.headers,
    content,
  });
 
  return Promise.reject(
    await fetchInterceptors.reject.reduce(
      async (output, interceptor) => await interceptor(internalURL, await output),
      Promise.resolve(error)
    )
  );
}
 
/**
 * Shorthand method for a DELETE request
 *
 * @param url The url you wish to fetch.
 * @param options The request options.
 * @returns The typed response or an error containing the `status` and the `content`
 */
rfetch.delete = <T>(url: string | URL, options?: RibbonFetchBodyOptions) => {
  return rfetch<T>(url, {
    ...options,
    method: 'DELETE',
  });
};
 
/* c8 ignore start */
export namespace rfetch {
  /* c8 ignore end */
 
  /**
   * Shorthand method for a GET request
   *
   * @param url The url you wish to fetch.
   * @param options The request options.
   * @returns The typed response or an error containing the `status` and the `content`
   */
  export async function get<T>(url: string | URL, options?: RibbonFetchBasicOptions) {
    return rfetch<T>(url, {
      ...options,
      method: 'GET',
    });
  }
 
  /**
   * Shorthand method for a PUT request
   *
   * @param url The url you wish to fetch.
   * @param options The request options.
   * @returns The typed response or an error containing the `status` and the `content`
   */
  export async function put<T>(url: string | URL, options?: RibbonFetchBodyOptions) {
    return rfetch<T>(url, {
      ...options,
      method: 'PUT',
    });
  }
 
  /**
   * Shorthand method for a POST request
   *
   * @param url The url you wish to fetch.
   * @param options The request options.
   * @returns The typed response or an error containing the `status` and the `content`
   */
  export async function post<T>(url: string | URL, options?: RibbonFetchBodyOptions) {
    return rfetch<T>(url, {
      ...options,
      method: 'POST',
    });
  }
 
  /**
   * Shorthand method for a PATCH request
   *
   * @param url The url you wish to fetch.
   * @param options The request options.
   * @returns The typed response or an error containing the `status` and the `content`
   */
  export async function patch<T>(url: string | URL, options?: RibbonFetchBodyOptions) {
    return rfetch<T>(url, {
      ...options,
      method: 'PATCH',
    });
  }
 
  /**
   * Shorthand method for a DELETE request
   *
   * @param url The url you wish to fetch.
   * @param options The request options.
   * @returns The typed response or an error containing the `status` and the `content`
   * @deprecated in favor of {@link rfetch.delete}
   */
  export async function remove<T>(url: string | URL, options?: RibbonFetchBodyOptions) {
    return rfetch.delete<T>(url, options);
  }
 
  export async function delimiters(type: DelimiterType) {
    delimiter = type;
  }
 
  export const interceptors = {
    request: {
      add(interceptor: RibbonRequestInterceptor) {
        fetchInterceptors.request.push(interceptor);
      },
 
      remove(interceptor: RibbonRequestInterceptor) {
        const index = fetchInterceptors.request.indexOf(interceptor);
 
        if (index === -1) return;
 
        fetchInterceptors.request.splice(index, 1);
      },
 
      clear() {
        fetchInterceptors.request = [];
      },
    },
 
    reject: {
      add(interceptor: RibbonRejectInterceptor) {
        fetchInterceptors.reject.push(interceptor);
      },
 
      remove(interceptor: RibbonRejectInterceptor) {
        const index = fetchInterceptors.reject.indexOf(interceptor);
 
        if (index === -1) return;
 
        fetchInterceptors.reject.splice(index, 1);
      },
 
      clear() {
        fetchInterceptors.reject = [];
      },
    },
 
    clear() {
      fetchInterceptors.reject = [];
      fetchInterceptors.request = [];
    },
  };
 
  export namespace is {
    export function error<T = any>(value: any): value is RibbonFetchError<T> {
      return value instanceof RibbonFetchError;
    }
  }
}