84 lines
2.4 KiB
TypeScript
84 lines
2.4 KiB
TypeScript
import { handleNetworkError } from "../shared/errors.js";
|
|
import { instanciateData } from "../shared/instanciateData.js";
|
|
import { authService, AuthService } from "./AuthService.js";
|
|
import { AppData, AppDataAndChanges } from "./DataStore.js";
|
|
|
|
export class RemoteStore {
|
|
#authService: AuthService;
|
|
|
|
constructor(authService: AuthService) {
|
|
this.#authService = authService;
|
|
}
|
|
|
|
async getAppData(): Promise<AppData> {
|
|
const result = await fetch("/api/user-data", {
|
|
headers: { Authorization: `Bearer ${this.#authService.getToken()}` },
|
|
});
|
|
await handleNetworkError(result);
|
|
const data: AppData = await result.json();
|
|
return instanciateData(data);
|
|
}
|
|
|
|
async sendChanges({ appData, changes }: AppDataAndChanges): Promise<AppData> {
|
|
const result = await fetch("/api/user-data", {
|
|
method: "PUT",
|
|
body: JSON.stringify({ userData: appData, changes }),
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${this.#authService.getToken()}`,
|
|
},
|
|
});
|
|
await handleNetworkError(result);
|
|
const data: AppData = await result.json();
|
|
return instanciateData(data);
|
|
}
|
|
|
|
async import(file: File) {
|
|
const result = await fetch("/api/import", {
|
|
method: "POST",
|
|
headers: { Authorization: `Bearer ${this.#authService.getToken()}` },
|
|
body: file,
|
|
});
|
|
await handleNetworkError(result);
|
|
}
|
|
|
|
async exportJson() {
|
|
const result = await fetch("/api/export", {
|
|
headers: { Authorization: `Bearer ${this.#authService.getToken()}` },
|
|
});
|
|
await handleNetworkError(result);
|
|
this.#download(
|
|
await result.text(),
|
|
`flip-flip-flip-${Temporal.Now.plainDateISO()}.json`,
|
|
"application/json",
|
|
);
|
|
}
|
|
|
|
async exportCsv() {
|
|
const result = await fetch("/api/export", {
|
|
headers: {
|
|
Authorization: `Bearer ${this.#authService.getToken()}`,
|
|
Accept: "text/csv",
|
|
},
|
|
});
|
|
await handleNetworkError(result);
|
|
this.#download(
|
|
await result.text(),
|
|
`flip-flip-flip-${Temporal.Now.plainDateISO()}.csv`,
|
|
"text/csv",
|
|
);
|
|
}
|
|
|
|
#download(content: string, filename: string, mimeType: string) {
|
|
const blob = new Blob([content], { type: mimeType });
|
|
const link = document.createElement("a");
|
|
const url = URL.createObjectURL(blob);
|
|
link.href = url;
|
|
link.download = filename;
|
|
link.click();
|
|
URL.revokeObjectURL(url);
|
|
}
|
|
}
|
|
|
|
export const remoteStore = new RemoteStore(authService);
|