Browse Source

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

master
Youen Toupin 3 years ago
parent
commit
fd444202e0
  1. 6
      WebApp/src/dashboard-page.tsx
  2. 16
      WebApp/src/monitor-api.ts
  3. 6
      WebApp/src/raw-data-page.tsx

6
WebApp/src/dashboard-page.tsx

@ -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);
}

16
WebApp/src/monitor-api.ts

@ -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;
}
}

6
WebApp/src/raw-data-page.tsx

@ -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);
}

Loading…
Cancel
Save