tuitio-client/src/client.ts

70 lines
1.8 KiB
TypeScript

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;
}
}
export type TuitioToken = { raw: string; validFrom: Date; validUntil: Date };
export type TuitioAuthenticationResult = { token: TuitioToken; status: string };
class TuitioClient {
baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
async authenticate(userName: string, password: string): Promise<TuitioAuthenticationResult> {
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);
}
};
export type TuitioState = { token: string; userName: string };
const fetch = (): TuitioState => {
const data = {
token: getItem(storageKeys.TOKEN),
userName: getItem(storageKeys.USER)
};
return data;
};
export { TuitioClient, invalidate, fetch };
export default TuitioClient;