summaryrefslogtreecommitdiff
path: root/packages/aml-backoffice-ui/src/hooks/useBackend.ts
blob: 0615c9c99aacfcde340f00f7747bec7d9cc720ef (plain)
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
import { canonicalizeBaseUrl } from "@gnu-taler/taler-util";
import {
  HttpResponseOk,
  RequestOptions,
  useApiContext,
} from "@gnu-taler/web-util/browser";
import { useCallback } from "preact/hooks";
import { uiSettings } from "../settings.js";

interface useBackendType {
  request: <T>(
    path: string,
    options?: RequestOptions,
  ) => Promise<HttpResponseOk<T>>;
  fetcher: <T>(args: [string, string]) => Promise<HttpResponseOk<T>>;
  paginatedFetcher: <T>(
    args: [string, number, number, string],
  ) => Promise<HttpResponseOk<T>>;
}
export function usePublicBackend(): useBackendType {
  const { request: requestHandler } = useApiContext();

  const baseUrl = getInitialBackendBaseURL();

  const request = useCallback(
    function requestImpl<T>(
      path: string,
      options: RequestOptions = {},
    ): Promise<HttpResponseOk<T>> {
      return requestHandler<T>(baseUrl, path, options);
    },
    [baseUrl],
  );

  const fetcher = useCallback(
    function fetcherImpl<T>([endpoint, talerAmlOfficerSignature]: [string, string]): Promise<HttpResponseOk<T>> {
      return requestHandler<T>(baseUrl, endpoint, {
        talerAmlOfficerSignature
      });
    },
    [baseUrl],
  );
  const paginatedFetcher = useCallback(
    function fetcherImpl<T>([endpoint, page, size, talerAmlOfficerSignature]: [
      string,
      number,
      number,
      string,
    ]): Promise<HttpResponseOk<T>> {
      return requestHandler<T>(baseUrl, endpoint, {
        params: { page: page || 1, size },
        talerAmlOfficerSignature,
      });
    },
    [baseUrl],
  );
  return {
    request,
    fetcher,
    paginatedFetcher,
  };
}

export function getInitialBackendBaseURL(): string {
  const overrideUrl =
    typeof localStorage !== "undefined"
      ? localStorage.getItem("exchange-base-url")
      : undefined;

  let result: string;

  if (!overrideUrl) {
    //normal path
    if (!uiSettings.backendBaseURL) {
      console.error(
        "ERROR: backendBaseURL was overridden by a setting file and missing. Setting value to 'window.origin'",
      );      
      result = typeof (window as any) !== "undefined" ? window.origin : "localhost"
    } else {
      result = uiSettings.backendBaseURL;
    }
  } else {
    // testing/development path
    result = overrideUrl
  }
  try {
    return canonicalizeBaseUrl(result)
  } catch (e) {
    //fall back
    return canonicalizeBaseUrl(window.origin)
  }
}