Refactored API access to cache/reuse the last result when changing page

This commit is contained in:
Youen Toupin 2022-04-04 22:35:03 +02:00
parent 7c13b98aba
commit fd444202e0
3 changed files with 20 additions and 8 deletions

View File

@ -2,11 +2,11 @@ import m from 'mithril';
import { MonitorApi, Status } from './monitor-api';
export default class DashboardPage {
api = new MonitorApi();
status?: Status;
status: Status = null;
autoRefresh = true;
oninit() {
this.status = MonitorApi.get().getStatus();
this.refresh();
}
@ -15,7 +15,7 @@ export default class DashboardPage {
}
async refresh() {
this.status = await this.api.getStatus();
this.status = await MonitorApi.get().fetchStatus();
if(this.autoRefresh)
setTimeout(() => { if(this.autoRefresh) this.refresh(); }, 500);
}

View File

@ -18,12 +18,22 @@ interface ApiStatus {
export class MonitorApi {
private mockServer: boolean;
private lastStatus: Status = null;
private static api: MonitorApi = null;
constructor() {
this.mockServer = window.location.protocol == "file:";
}
async getStatus(): Promise<Status> {
static get() {
if(MonitorApi.api == null)
MonitorApi.api = new MonitorApi();
return MonitorApi.api;
}
getStatus() { return this.lastStatus; }
async fetchStatus(): Promise<Status> {
let apiStatus: ApiStatus;
if(this.mockServer) {
@ -43,12 +53,14 @@ export class MonitorApi {
});
}
return {
this.lastStatus = {
batteryVoltage: apiStatus.v / 1000,
motorCurrent: apiStatus.c / 1000,
speed: apiStatus.s / 1000,
temperature: apiStatus.t / 10,
altitude: apiStatus.alt / 1000
};
return this.lastStatus;
}
}

View File

@ -4,11 +4,11 @@ import { MonitorApi, Status } from './monitor-api';
require("./raw-data-page.css");
export default class RawDataPage {
api = new MonitorApi();
status?: Status;
status: Status = null;
autoRefresh = true;
oninit() {
this.status = MonitorApi.get().getStatus();
this.refresh();
}
@ -17,7 +17,7 @@ export default class RawDataPage {
}
async refresh() {
this.status = await this.api.getStatus();
this.status = await MonitorApi.get().fetchStatus();
if(this.autoRefresh)
setTimeout(() => { if(this.autoRefresh) this.refresh(); }, 500);
}