@/utils#extractContentType TypeScript Examples

The following examples show how to use @/utils#extractContentType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From electron-request with MIT License 5 votes vote down vote up
getRequestOptions = (constructorOptions: RequestConstructorOptions): RequestOptions => {
  const options = { ...DEFAULT_OPTIONS, ...constructorOptions };

  const method = options.method.toUpperCase();
  const { body, requestURL, query, headers: headerOptions } = options;

  if (body !== null && (method === METHOD_MAP.GET || method === METHOD_MAP.HEAD)) {
    throw new TypeError('Request with GET/HEAD method cannot have body');
  }

  const parsedURL = new URL(requestURL);
  if (!parsedURL.protocol || !parsedURL.hostname) {
    throw new TypeError('Only absolute URLs are supported');
  }
  if (!/^https?:$/.test(parsedURL.protocol)) {
    throw new TypeError('Only HTTP(S) protocols are supported');
  }
  if (query) {
    for (const [queryKey, queryValue] of Object.entries(query)) {
      parsedURL.searchParams.append(queryKey, queryValue);
    }
  }

  const headers = new Headers(headerOptions);
  // User cannot set content-length themself as per fetch spec
  headers.delete(HEADER_MAP.CONTENT_LENGTH);
  // Add compression header
  headers.set(HEADER_MAP.ACCEPT_ENCODING, SUPPORTED_COMPRESSIONS.join(','));
  // Add accept header
  if (!headers.has(HEADER_MAP.ACCEPT)) {
    headers.set(HEADER_MAP.ACCEPT, '*/*');
  }
  // Add connection header
  if (!headers.has(HEADER_MAP.CONNECTION)) {
    headers.set(HEADER_MAP.CONNECTION, 'close');
  }
  // Add content type header
  if (body && !headers.has(HEADER_MAP.CONTENT_TYPE)) {
    const contentType = extractContentType(body);
    if (contentType) {
      headers.append(HEADER_MAP.CONTENT_TYPE, contentType);
    }
  }

  return {
    ...options,
    method,
    parsedURL,
    headers,
  };
}