67 lines
1.6 KiB
TypeScript
67 lines
1.6 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;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class TuitioConnector {
|
||
|
baseUrl: string;
|
||
|
|
||
|
constructor(baseUrl: string) {
|
||
|
this.baseUrl = baseUrl;
|
||
|
}
|
||
|
|
||
|
async authenticate(userName: string, password: string) {
|
||
|
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);
|
||
|
}
|
||
|
};
|
||
|
|
||
|
type TuitioState = { token: string; userName: string };
|
||
|
|
||
|
const fetch = (): TuitioState => {
|
||
|
const data = {
|
||
|
token: getItem(storageKeys.TOKEN),
|
||
|
userName: getItem(storageKeys.USER)
|
||
|
};
|
||
|
|
||
|
return data;
|
||
|
};
|
||
|
|
||
|
export { TuitioConnector, invalidate, fetch };
|
||
|
export default TuitioConnector;
|