tuitio-client/src/client.ts

74 lines
2.0 KiB
TypeScript

import axios from "axios";
import { localStorage } from "@flare/js-utils";
import { storageKeys } from "./constants";
import { getUrlTemplates } from "./config";
import { isValidURL } from "./utils";
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) {
const { detail, title } = error.response.data;
throw {
...error.response.data,
message: detail || title
};
}
throw error;
}
}
export type TuitioToken = { raw: string; validFrom: Date; validUntil: Date };
export type TuitioAuthenticationResult = { token: TuitioToken; status: string };
class TuitioClient {
tuitioUrl: string;
constructor(tuitioUrl: string | null) {
if (tuitioUrl === null || tuitioUrl === "" || isValidURL(tuitioUrl) === false) {
throw new Error(`TuitioClient: ${tuitioUrl} is not a valid URL.`);
}
this.tuitioUrl = tuitioUrl;
}
async authenticate(userName: string, password: string): Promise<TuitioAuthenticationResult> {
const templates = getUrlTemplates(this.tuitioUrl);
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);
}
};
export type TuitioState = { token: TuitioToken; userName: string };
const fetch = (): TuitioState => {
const data = {
token: getItem(storageKeys.TOKEN),
userName: getItem(storageKeys.USER)
};
return data;
};
export { TuitioClient, invalidate, fetch };
export default TuitioClient;