forked from PolicyEngine/policyengine-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metadata_fetch.mjs
73 lines (65 loc) · 1.93 KB
/
metadata_fetch.mjs
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import fetch from "node-fetch";
import fs from "fs";
import path from "path";
let metadataUS = null;
let metadataUK = null;
let metadataCA = null;
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const filePath = path.join(
__dirname,
"src",
"__tests__",
"__setup__",
"data.json",
);
/**
* Replaces Response.json(), which unfortunately has no
* native way of passing a reviver
*
* This function is copied, instead of imported, due to
* limitations of Jest within ES6+ module environment
* @param {Response} response The response object
* @returns {Promise} The JSON object, parsed with custom reviver
*/
function wrappedResponseJson(response) {
return new Promise((resolve, reject) => {
response.text().then((text) => {
resolve(wrappedJsonParse(text));
});
});
}
function wrappedJsonParse() {
return JSON.parse(...arguments, JsonReviver);
}
function JsonReviver(key, value) {
if (value === "Infinity") {
return Infinity;
}
if (value === "-Infinity") {
return -Infinity;
}
return value;
}
async function fetchMetadata(countryId) {
const res = await fetch(`https://api.policyengine.org/${countryId}/metadata`);
// For the time being, this is being kept as res.json(), unlike
// the rest of the repo, due to Jest's challenges with ES6 modules
const metadataRaw = await wrappedResponseJson(res);
const metadata = metadataRaw.result;
return metadata;
}
metadataUS = await fetchMetadata("us");
metadataUK = await fetchMetadata("uk");
metadataCA = await fetchMetadata("ca");
let jsonData = {
metadataUS: metadataUS,
metadataUK: metadataUK,
metadataCA: metadataCA,
};
// For the time being, this is being kept as res.json(), unlike
// the rest of the repo, due to Jest's challenges with ES6 modules
jsonData = JSON.stringify(jsonData);
fs.writeFile(filePath, jsonData, (err) => {
if (err) throw err;
console.log("Data has been written to src/__tests__/__setup__/data.json");
});