2023-02-10 01:27:38 +02:00
|
|
|
import axios from "axios";
|
|
|
|
import { localStorage } from "@flare/js-utils";
|
|
|
|
import { storageKeys } from "./constants";
|
|
|
|
import { getUrlTemplates } from "./config";
|
|
|
|
|
|
|
|
const { setItem, getItem, removeItem } = localStorage;
|
|
|
|
|
|
|
|
async function request(url: string, method: string) {
|
|
|
|
try {
|
|
|
|
const res = await axios.request({ url, method });
|
|
|
|
return res.data;
|
|
|
|
} catch (error: any) {
|
|
|
|
if (error.response && error.response.data) {
|
|
|
|
throw (
|
|
|
|
{
|
|
|
|
...error.response.data,
|
|
|
|
message: error.response.data.detail || error.response.data.title
|
|
|
|
} || error
|
|
|
|
);
|
|
|
|
}
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-11 02:21:30 +02:00
|
|
|
export type TuitioToken = { raw: string; validFrom: Date; validUntil: Date };
|
|
|
|
export type TuitioAuthenticationResult = { token: TuitioToken; status: string };
|
|
|
|
|
2023-02-10 01:29:28 +02:00
|
|
|
class TuitioClient {
|
2023-02-10 01:27:38 +02:00
|
|
|
baseUrl: string;
|
|
|
|
|
|
|
|
constructor(baseUrl: string) {
|
|
|
|
this.baseUrl = baseUrl;
|
|
|
|
}
|
|
|
|
|
2023-02-11 02:21:30 +02:00
|
|
|
async authenticate(userName: string, password: string): Promise<TuitioAuthenticationResult> {
|
2023-02-10 01:27:38 +02:00
|
|
|
const templates = getUrlTemplates(this.baseUrl);
|
|
|
|
const url = templates.authentication.replace("{username}", userName).replace("{password}", password);
|
|
|
|
|
|
|
|
const response = await request(url, "post");
|
|
|
|
if (response.token) {
|
|
|
|
setItem(storageKeys.TOKEN, response.token);
|
|
|
|
setItem(storageKeys.USER, userName);
|
|
|
|
}
|
|
|
|
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const invalidate = (): void => {
|
|
|
|
const token = getItem(storageKeys.TOKEN);
|
|
|
|
if (token) {
|
|
|
|
removeItem(storageKeys.TOKEN);
|
|
|
|
removeItem(storageKeys.USER);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-02-10 01:45:27 +02:00
|
|
|
export type TuitioState = { token: string; userName: string };
|
2023-02-10 01:27:38 +02:00
|
|
|
|
|
|
|
const fetch = (): TuitioState => {
|
|
|
|
const data = {
|
|
|
|
token: getItem(storageKeys.TOKEN),
|
|
|
|
userName: getItem(storageKeys.USER)
|
|
|
|
};
|
|
|
|
|
|
|
|
return data;
|
|
|
|
};
|
|
|
|
|
2023-02-10 01:29:28 +02:00
|
|
|
export { TuitioClient, invalidate, fetch };
|
|
|
|
export default TuitioClient;
|