forked from binary-smith/currency-conversion-rate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvenience.js
More file actions
42 lines (40 loc) · 1.36 KB
/
convenience.js
File metadata and controls
42 lines (40 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import Soup from 'gi://Soup';
/**
* Atomically write a JS object as JSON to `path`.
*/
export function saveJSON(path, data) {
const file = Gio.File.new_for_path(path);
file.replace_contents(
JSON.stringify(data, null, 2),
null, false,
Gio.FileCreateFlags.REPLACE_DESTINATION,
null
);
}
/**
* Fetch `url` via `session` and return the parsed JSON.
* Rejects with a descriptive Error on network or HTTP failure.
*/
export function fetchJSON(session, url) {
const msg = Soup.Message.new('GET', url);
return new Promise((resolve, reject) => {
session.send_and_read_async(msg, GLib.PRIORITY_DEFAULT, null, (s, result) => {
if (msg.get_status() === Soup.Status.CANCELLED) {
reject(new Error('Request was cancelled.'));
return;
}
try {
const bytes = s.send_and_read_finish(result);
if (msg.get_status() !== Soup.Status.OK)
throw new Error(`HTTP ${msg.get_status()} for ${url}`);
if (!bytes?.get_size())
throw new Error(`Empty response from ${url}`);
resolve(JSON.parse(new TextDecoder().decode(bytes.get_data())));
} catch (e) {
reject(e);
}
});
});
}