DRY fetch calls in _shared.js
This commit is contained in:
parent
c012e496ff
commit
0c110b5498
27
_shared.js
27
_shared.js
|
@ -5,7 +5,16 @@ import * as path from 'node:path';
|
|||
const emitWarning = process.emitWarning.bind(process);
|
||||
process.emitWarning = (...args) => args[1] !== 'ExperimentalWarning' && emitWarning(...args);
|
||||
|
||||
export const make_query = (params) => {
|
||||
const fetch_200 = async (...args) => {
|
||||
const resp = await fetch(...args);
|
||||
if (resp.status !== 200) {
|
||||
console.log(...args);
|
||||
throw resp;
|
||||
}
|
||||
return resp;
|
||||
};
|
||||
|
||||
const make_query = (params) => {
|
||||
const filtered = {};
|
||||
for (const key in params) {
|
||||
if (params[key] != null) {
|
||||
|
@ -16,22 +25,10 @@ export const make_query = (params) => {
|
|||
return str && `?${str}`;
|
||||
};
|
||||
|
||||
export const make_request = async (path, params) => {
|
||||
const url = path + make_query(params);
|
||||
const resp = await fetch(url);
|
||||
if (resp.status !== 200) {
|
||||
console.log(url);
|
||||
throw resp;
|
||||
}
|
||||
return resp;
|
||||
};
|
||||
export const make_request = (url, params) => fetch_200(url + make_query(params));
|
||||
|
||||
export const download_to = async (url, dest, date) => {
|
||||
const resp = await fetch(url);
|
||||
if (resp.status !== 200) {
|
||||
console.log(url);
|
||||
throw resp;
|
||||
}
|
||||
const resp = await fetch_200(url);
|
||||
const buffer = Buffer.from(await resp.arrayBuffer());
|
||||
const tmp = crypto.randomUUID();
|
||||
await fs.promises.writeFile(tmp, buffer);
|
||||
|
|
Loading…
Reference in New Issue