armisa-models
Version:
models of armisa!
66 lines (56 loc) • 2.36 kB
text/typescript
import { AxiosError } from "axios";
import { ElementsOfFormFactory } from "../../../Page/ElementsOfFormFactory";
import { AuthFactory, ILoginResponse } from "../../AuthFactory";
import { useAxios, useUrls } from "../../Models/StorageManager/TokenInfo";
export class LoginByToken {
public static createNew(authFactory: AuthFactory): LoginByToken | null {
if (authFactory.mainStateManager.tokenInfo.tokenFromLocalStorage) {
return new LoginByToken(authFactory);
}
return null;
}
#urls = useUrls('BaseCode', 'auth');
#apiAxios = useAxios(this.#urls);
private constructor(public authFactory: AuthFactory) {
}
get #elementsOfForm(): ElementsOfFormFactory {
return this.authFactory.elementsOfForm;
}
login = () => {
this.#elementsOfForm.showWaitingFormSpinner();
this.loginAxios().then(response => {
if (response.isSuccess) {
this.#elementsOfForm.closeWaitingFormSpinner();
} else {
this.#elementsOfForm.closeWaitingFormSpinner();
this.#elementsOfForm.showInvalidArgumentMessageBox(response.message);
}
}).catch(error => {
this.#elementsOfForm.closeWaitingFormSpinner();
this.#elementsOfForm.showErrorMessageBox(error);
});
}
loginAxios = (): Promise<ILoginResponse> => {
return new Promise<ILoginResponse>((resolve, reject) => {
this.#apiAxios.get<ILoginResponse>(this.#urls.tokenValidation).then((res) => {
if (res.status === 200) {
this.authFactory.logedIn(res.data, true, this.routerPath);
resolve(res.data);
} else {
reject(`requeset to ${this.controllerPath}/${this.actionPath} reject by status : ${res.status} ${res.statusText}`);
}
}).catch((error: AxiosError) => {
reject(`exception error on login user error : ${error}`);
});
});
}
public get controllerPath(): string {
return this.#urls.controller;
}
public get actionPath(): string {
return this.#urls.tokenValidation;
}
public get routerPath(): string {
return '/login';
}
}