tuitio-client/src/client.ts

69 lines
1.8 KiB
TypeScript
Raw Normal View History

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) {
2023-02-11 04:01:15 +02:00
const { detail, title } = error.response.data;
throw {
...error.response.data,
message: detail || title
};
2023-02-10 01:27:38 +02:00
}
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-11 05:31:25 +02:00
export type TuitioState = { token: TuitioToken; 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;