summaryrefslogtreecommitdiff
path: root/packages/demobank-ui/src/hooks/config.ts
blob: 4cf677d357e64111abf256db39e5fa13b30861b1 (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
import { LibtoolVersion } from "@gnu-taler/taler-util";
import { ErrorType, HttpError, HttpResponseServerError, RequestError, useApiContext } from "@gnu-taler/web-util/browser";
import { useEffect, useState } from "preact/hooks";
import { getInitialBackendBaseURL } from "./backend.js";

/**
 * Protocol version spoken with the bank.
 *
 * Uses libtool's current:revision:age versioning.
 */
export const BANK_INTEGRATION_PROTOCOL_VERSION = "0:0:0";

async function getConfigState(
  request: ReturnType<typeof useApiContext>["request"],
): Promise<SandboxBackend.Config> {
  const url = getInitialBackendBaseURL();
  const result = await request<SandboxBackend.Config>(url, `config`);
  return result.data;
}

export function useConfigState(): undefined | true | string | HttpError<SandboxBackend.SandboxError> {
  const [checked, setChecked] = useState<true | string | HttpError<SandboxBackend.SandboxError>>()
  const { request } = useApiContext();

  useEffect(() => {
    getConfigState(request)
      .then((s) => {
        const r = LibtoolVersion.compare(BANK_INTEGRATION_PROTOCOL_VERSION, s.version)
        if (r?.compatible) {
          setChecked(true);
        } else {
          setChecked(s.version)
        }
      })
      .catch((error: unknown) => {
        if (error instanceof RequestError) {
          setChecked(error.cause);
        }
      });
  }, []);

  return checked;
}