wallet-core/packages/demobank-ui/src/hooks/backend.ts

75 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-12-09 13:09:20 +01:00
/*
This file is part of GNU Taler
(C) 2022 Taler Systems S.A.
GNU Taler is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
2022-12-09 15:58:39 +01:00
import { useLocalStorage } from "@gnu-taler/web-util/lib/index.browser";
2022-12-07 13:29:36 +01:00
/**
* Has the information to reach and
* authenticate at the bank's backend.
*/
2022-12-07 22:45:49 +01:00
export type BackendState = LoggedIn | LoggedOut;
export interface BackendInfo {
url: string;
username: string;
password: string;
}
interface LoggedIn extends BackendInfo {
2022-12-07 22:45:49 +01:00
status: "loggedIn";
}
interface LoggedOut {
2022-12-07 22:45:49 +01:00
status: "loggedOut";
2022-12-07 13:29:36 +01:00
}
2022-12-07 22:45:49 +01:00
export const defaultState: BackendState = { status: "loggedOut" };
export interface BackendStateHandler {
2022-12-07 22:45:49 +01:00
state: BackendState;
clear(): void;
save(info: BackendInfo): void;
}
2022-12-07 13:29:36 +01:00
/**
* Return getters and setters for
* login credentials and backend's
* base URL.
*/
export function useBackendState(): BackendStateHandler {
2022-12-09 15:58:39 +01:00
const [value, update] = useLocalStorage(
2022-12-07 22:45:49 +01:00
"backend-state",
JSON.stringify(defaultState),
);
// const parsed = value !== undefined ? JSON.parse(value) : value;
2022-12-07 22:45:49 +01:00
let parsed;
try {
2022-12-07 22:45:49 +01:00
parsed = JSON.parse(value!);
} catch {
2022-12-07 22:45:49 +01:00
parsed = undefined;
}
2022-12-07 22:45:49 +01:00
const state: BackendState = !parsed?.status ? defaultState : parsed;
return {
state,
clear() {
2022-12-07 22:45:49 +01:00
update(JSON.stringify(defaultState));
},
save(info) {
2022-12-07 22:45:49 +01:00
const nextState: BackendState = { status: "loggedIn", ...info };
update(JSON.stringify(nextState));
},
2022-12-07 22:45:49 +01:00
};
2022-12-07 13:29:36 +01:00
}