Farmbot-Web-App/frontend/account/request_account_export.ts

43 lines
1.4 KiB
TypeScript
Raw Normal View History

import { API } from "../api";
import { Content } from "../constants";
2019-06-24 15:39:49 -06:00
import { success } from "../toast/toast";
import axios, { AxiosResponse } from "axios";
2018-10-22 08:01:06 -06:00
import { DeviceAccountSettings } from "farmbot/dist/resources/api_resources";
2019-04-02 13:59:37 -06:00
import { t } from "../i18next_wrapper";
2018-05-07 08:57:02 -06:00
interface DataDumpExport { device?: DeviceAccountSettings; }
type Response = AxiosResponse<DataDumpExport | undefined>;
export function generateFilename({ device }: DataDumpExport): string {
let name: string;
name = device ? (device.name + "_" + device.id) : "farmbot";
2018-05-07 09:40:14 -06:00
return `export_${name}.json`.toLowerCase();
2018-05-07 08:57:02 -06:00
}
// Thanks, @KOL - https://stackoverflow.com/a/19328891/1064917
export function jsonDownload(data: object, fname = generateFilename(data)) {
// When email is not available on the API (self hosted).
// Will synchronously load backup over the wire (slow)
const a = document.createElement("a");
document.body.appendChild(a);
a.style.display = "none";
const json = JSON.stringify(data),
blob = new Blob([json], { type: "octet/stream" }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fname;
a.click();
window.URL.revokeObjectURL(url);
return a;
}
2018-05-07 08:57:02 -06:00
const ok = (resp: Response) => {
const { data } = resp;
return data ? jsonDownload(data) : success(t(Content.EXPORT_SENT));
};
export const requestAccountExport =
() => axios
.post(API.current.exportDataPath)
.then(ok);