You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.8 KiB
51 lines
1.8 KiB
7 years ago
|
import { createBrowserHistory, History } from "history";
|
||
7 years ago
|
import { computed } from "mobx";
|
||
7 years ago
|
import { RouterStore, syncHistoryWithStore } from "mobx-react-router";
|
||
7 years ago
|
|
||
7 years ago
|
import { WebSocketRpcClient } from "@client/sprinklersRpc/WebSocketRpcClient";
|
||
|
import HttpApi from "@client/state/HttpApi";
|
||
|
import { UiStore } from "@client/state/UiStore";
|
||
7 years ago
|
import ApiError from "@common/ApiError";
|
||
|
import { ErrorCode } from "@common/ErrorCode";
|
||
7 years ago
|
import log from "@common/logger";
|
||
|
|
||
7 years ago
|
export default class AppState {
|
||
|
history: History = createBrowserHistory();
|
||
7 years ago
|
routerStore = new RouterStore();
|
||
7 years ago
|
uiStore = new UiStore();
|
||
|
httpApi = new HttpApi();
|
||
7 years ago
|
tokenStore = this.httpApi.tokenStore;
|
||
7 years ago
|
sprinklersRpc = new WebSocketRpcClient(this.tokenStore);
|
||
7 years ago
|
|
||
7 years ago
|
@computed get isLoggedIn() {
|
||
|
return this.tokenStore.accessToken.isValid;
|
||
|
}
|
||
|
|
||
7 years ago
|
async start() {
|
||
7 years ago
|
syncHistoryWithStore(this.history, this.routerStore);
|
||
|
|
||
|
this.tokenStore.loadLocalStorage();
|
||
|
|
||
7 years ago
|
if (!this.httpApi.tokenStore.accessToken.isValid) {
|
||
|
if (this.httpApi.tokenStore.refreshToken.isValid) {
|
||
7 years ago
|
try {
|
||
|
await this.httpApi.tokenStore.grantRefresh();
|
||
|
} catch (err) {
|
||
7 years ago
|
if (err instanceof ApiError && err.code === ErrorCode.BadToken) {
|
||
|
log.warn({ err }, "refresh is bad for some reason, erasing");
|
||
|
this.tokenStore.clear();
|
||
|
this.history.push("/login");
|
||
|
} else {
|
||
|
log.error({ err }, "could not refresh access token");
|
||
|
// TODO: some kind of error page?
|
||
|
}
|
||
7 years ago
|
}
|
||
7 years ago
|
} else {
|
||
7 years ago
|
this.history.push("/login");
|
||
7 years ago
|
}
|
||
|
}
|
||
|
|
||
7 years ago
|
this.sprinklersRpc.start();
|
||
7 years ago
|
}
|
||
|
}
|