Skip to content

Instantly share code, notes, and snippets.

@gabssnake
Last active June 2, 2024 10:26
Show Gist options
  • Save gabssnake/0916d61089c5fd43d6772c8a726eecde to your computer and use it in GitHub Desktop.
Save gabssnake/0916d61089c5fd43d6772c8a726eecde to your computer and use it in GitHub Desktop.
Wrapper on `fetch` to get happy path or just `null` and stderr logs, instead of throwing errors
import assert from "node:assert/strict";
const { error: debug } = console;
/**
* Silly fetch wrapper for lazyness and convenience to get happy path JSON
* or just `null` and stderr logs, instead of fiddling with res or throwing.
* $ node --env-file=.env script.mjs
* $ TOKEN=xxx node script.mjs
*/
export async function safeFetch(url, { TOKEN } = process.env) {
assert(TOKEN, "You need to provide TOKEN in the environment");
debug(url);
const headers = {
Authorization: `Bearer ${TOKEN}`,
};
try {
let res = await fetch(url, { headers });
const body = await res.json();
if (res.ok === false) {
throw new Error(`${res.status} ${res.statusText} ${body.message}`);
}
return body;
} catch (err) {
debug(err.message);
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment