Ringtone app
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

63 рядки
1.4 KiB

  1. import {URLSearchParams} from 'url';
  2. export enum Method {
  3. HEAD = 'HEAD',
  4. GET = 'GET',
  5. POST = 'POST',
  6. PUT = 'PUT',
  7. PATCH = 'PATCH',
  8. DELETE = 'DELETE',
  9. }
  10. type Fetch = (input: RequestInfo, init?: RequestInit) => Promise<Response>
  11. type CreateFetchClientOptions = {
  12. baseUrl: string,
  13. headers?: HeadersInit,
  14. fetch?: Fetch,
  15. }
  16. export type FetchClientParams = {
  17. url: string,
  18. method: Method,
  19. body?: BodyInit,
  20. query?: URLSearchParams | string | NodeJS.Dict<string | ReadonlyArray<string>> | Iterable<[string, string]> | ReadonlyArray<[string, string]>,
  21. headers?: HeadersInit,
  22. fetch?: Fetch,
  23. }
  24. export type FetchClient = (params: FetchClientParams) => Promise<Response>
  25. type CreateFetchClient = (options: CreateFetchClientOptions) => FetchClient
  26. export const createFetchClient: CreateFetchClient = ({
  27. baseUrl,
  28. headers: defaultHeaders = {},
  29. fetch: f = fetch,
  30. }) => {
  31. return ({
  32. url,
  33. method,
  34. body,
  35. query,
  36. headers = {},
  37. fetch: ff = f,
  38. }) => {
  39. const theUrl = new URL(url, baseUrl)
  40. if (Boolean(query as unknown)) {
  41. theUrl.search = new URLSearchParams(query).toString()
  42. }
  43. return ff(theUrl.toString(), {
  44. method,
  45. body,
  46. // TODO handle any kind of headers init
  47. headers: {
  48. ...defaultHeaders,
  49. ...headers,
  50. },
  51. })
  52. }
  53. }
  54. export const createMockFetch = (body: BodyInit, response: ResponseInit): Fetch => async () => new Response(body, response)