feat(traffic): api support & adjust

This commit is contained in:
GyDi
2021-12-11 20:52:06 +08:00
parent 0028bef559
commit 0a3c59450b
4 changed files with 65 additions and 17 deletions

11
src/services/base.ts Normal file
View File

@@ -0,0 +1,11 @@
import axios from "axios";
const axiosIns = axios.create({
baseURL: "http://127.0.0.1:9090",
});
axiosIns.interceptors.response.use((respone) => {
return respone.data;
});
export default axiosIns;

5
src/services/index.ts Normal file
View File

@@ -0,0 +1,5 @@
import * as traffic from "./traffic";
export default {
...traffic,
};

29
src/services/traffic.ts Normal file
View File

@@ -0,0 +1,29 @@
import axios from "axios";
import axiosIns from "./base";
export interface TrafficData {
up: number;
down: number;
}
/// Get the traffic stream
export async function getTraffic(callback: (data: TrafficData) => void) {
const source = axios.CancelToken.source();
axiosIns.get("/traffic", {
cancelToken: source.token,
onDownloadProgress: (progressEvent) => {
const data = progressEvent.currentTarget.response || "";
const lastData = data.slice(data.trim().lastIndexOf("\n") + 1);
if (!lastData) callback({ up: 0, down: 0 });
try {
callback(JSON.parse(lastData) as TrafficData);
} catch {
callback({ up: 0, down: 0 });
}
},
});
return source;
}