Debian Codegraph @

frontend/src/api/index.ts

raw
1 import { get as store_get } from "svelte/store";
2
3 import type { Entry } from "../entries";
4 import { urlForRaw } from "../helpers";
5 import { fetchJSON } from "../lib/fetch";
6 import type { ValidationT } from "../lib/validation";
7 import { string } from "../lib/validation";
8 import { notify, notify_err } from "../notifications";
9 import router from "../router";
10 import type { Filters, FiltersConversionInterval } from "../stores/filters";
11 import type { GetAPIValidators, SourceFile } from "./validators";
12 import { getAPIValidators } from "./validators";
13
14 class InvalidResponseDataError extends Error {
15 constructor(cause: Error) {
16 super("Invalid data returned in API request.", { cause });
17 notify_err(this);
18 }
19 }
20
21 /** Required arguments for the various PUT API endpoints. */
22 interface PutAPIInputs {
23 add_document: FormData;
24 upload_import_file: FormData;
25 add_entries: { entries: Entry[] };
26 attach_document: { filename: string; entry_hash: string };
27 format_source: { source: string };
28 source: SourceFile;
29 source_slice: { entry_hash: string; source: string; sha256sum: string };
30 }
31
32 /**
33 * PUT to an API endpoint and convert the returned JSON data to an object.
34 * @param endpoint - the endpoint to fetch
35 * @param body - either a FormData instance or an object that will be converted
36 * to JSON.
37 * @returns the response message string
38 */
39 export async function put<T extends keyof PutAPIInputs>(
40 endpoint: T,
41 body: PutAPIInputs[T],
42 ): Promise<string> {
43 const opts =
44 body instanceof FormData
45 ? { body }
46 : {
47 headers: { "Content-Type": "application/json" },
48 body: JSON.stringify(body),
49 };
50 const $urlForRaw = store_get(urlForRaw);
51 const url = $urlForRaw(`api/${endpoint}`);
52 const json = await fetchJSON(url, { method: "PUT", ...opts });
53 const res = string(json);
54 if (res.is_ok) {
55 return res.value;
56 }
57 throw new InvalidResponseDataError(res.error);
58 }
59
60 interface GetAPIParams {
61 balance_sheet: FiltersConversionInterval;
62 account_report: FiltersConversionInterval & { a: string; r: string };
63 changed: undefined;
64 commodities: Filters;
65 context: { entry_hash: string };
66 documents: Filters;
67 errors: undefined;
68 events: Filters;
69 extract: { filename: string; importer: string };
70 imports: undefined;
71 income_statement: FiltersConversionInterval;
72 trial_balance: FiltersConversionInterval;
73 ledger_data: undefined;
74 move: { filename: string; account: string; new_name: string };
75 options: undefined;
76 payee_accounts: { payee: string };
77 payee_transaction: { payee: string };
78 query: Filters & { query_string: string };
79 source: { filename: string };
80 }
81
82 /**
83 * Fetch an API endpoint and convert the JSON data to an object.
84 * @param endpoint - the endpoint to fetch
85 * @param params - a string to append as params or an object.
86 * @returns the validated response returned by the endpoint.
87 */
88 export async function get<T extends keyof GetAPIParams>(
89 endpoint: T,
90 ...[params]: GetAPIParams[T] extends undefined
91 ? [undefined?, number?]
92 : [GetAPIParams[T], number?]
93 ): Promise<ValidationT<GetAPIValidators[T]>> {
94 const $urlForRaw = store_get(urlForRaw);
95 const url = $urlForRaw(`api/${endpoint}`, params);
96 const json = await fetchJSON(url);
97 const res = getAPIValidators[endpoint](json);
98 if (res.is_ok) {
99 return res.value as ValidationT<GetAPIValidators[T]>;
100 }
101 throw new InvalidResponseDataError(res.error);
102 }
103
104 interface DeleteAPIParams {
105 document: { filename: string };
106 source_slice: { entry_hash: string; sha256sum: string };
107 }
108
109 /**
110 * Delete an API endpoint and convert the JSON data to an object.
111 * @param endpoint - the endpoint to fetch
112 * @param params - a string to append as params or an object.
113 * @returns the response returned by the endpoint.
114 */
115 export async function doDelete<T extends keyof DeleteAPIParams>(
116 endpoint: T,
117 params: DeleteAPIParams[T],
118 ): Promise<string> {
119 const $urlForRaw = store_get(urlForRaw);
120 const url = $urlForRaw(`api/${endpoint}`, params);
121 const json = await fetchJSON(url, { method: "DELETE" });
122 const res = string(json);
123 if (res.is_ok) {
124 return res.value;
125 }
126 throw new InvalidResponseDataError(res.error);
127 }
128
129 /**
130 * Move a file, either in an import directory or a document.
131 * @param filename - the current name of the file.
132 * @param account - account to move the file to.
133 * @param new_name - the new filename.
134 * @returns whether the file was moved successfully.
135 */
136 export async function moveDocument(
137 filename: string,
138 account: string,
139 new_name: string,
140 ): Promise<boolean> {
141 try {
142 const msg = await get("move", { filename, account, new_name });
143 notify(msg);
144 return true;
145 } catch (error) {
146 notify_err(error);
147 return false;
148 }
149 }
150
151 /**
152 * Delete a file, either in an import directory or a document.
153 * @param filename - the filename of the file to delete.
154 * @returns whether the file was deleted successfully.
155 */
156 export async function deleteDocument(filename: string): Promise<boolean> {
157 try {
158 const msg = await doDelete("document", { filename });
159 notify(msg);
160 return true;
161 } catch (error) {
162 notify_err(error);
163 return false;
164 }
165 }
166
167 /**
168 * Save an array of entries.
169 * @param entries - an array of entries to save to the Beancount file.
170 */
171 export async function saveEntries(entries: Entry[]): Promise<void> {
172 if (!entries.length) {
173 return;
174 }
175 try {
176 const data = await put("add_entries", { entries });
177 router.reload();
178 notify(data);
179 } catch (error) {
180 notify_err(error, (e) => `Saving failed: ${e.message}`);
181 throw error;
182 }
183 }