Skip to content

Instantly share code, notes, and snippets.

@nwaughachukwuma
Created January 14, 2023 09:22
Show Gist options
  • Save nwaughachukwuma/05e900290e21410fabc032cc5e75689e to your computer and use it in GitHub Desktop.
Save nwaughachukwuma/05e900290e21410fabc032cc5e75689e to your computer and use it in GitHub Desktop.
Nyre-Fetch is a simple Node.js wrapper built on top of node-fetch. It includes helper methods I find helpful and use in my projects.
import nodeFetch, { type RequestInit, type Response } from "node-fetch";
import type { AbortSignal } from "abort-controller";
const TEN_MEGABYTES = 1000 * 1000 * 10;
type StreamOptions = RequestInit & {
signal?: AbortSignal;
highWaterMark?: number;
};
export async function fetch(
url: string,
options?: RequestInit
): Promise<Response> {
return nodeFetch(url, { highWaterMark: TEN_MEGABYTES, ...options });
}
const nyreFetch = {
post(path: string, body: any, options?: RequestInit) {
return fetch(path, {
...options,
method: "POST",
body: JSON.stringify(body),
});
},
get(path: string, options?: RequestInit) {
return fetch(path, { ...options, method: "GET" });
},
put(path: string, body: any, options?: RequestInit) {
return fetch(path, {
...options,
method: "PUT",
body: JSON.stringify(body),
});
},
delete(path: string, options?: RequestInit) {
return fetch(path, { ...options, method: "DELETE" });
},
head(path: string, options?: RequestInit) {
return fetch(path, { ...options, method: "HEAD" });
},
async stream(source: string, options?: StreamOptions) {
const response = await fetch(source, {
...options,
signal: options?.signal,
highWaterMark: options?.highWaterMark ?? TEN_MEGABYTES,
});
if (!response.ok || !response.body) {
throw new Error(`Failed to read stream path: ${source}`);
}
return response.body;
},
};
function getFullURL(baseUrl: string, path: string) {
baseUrl = baseUrl.replace(/\/$/, "");
path = path.replace(/^\//, "");
return `${baseUrl}/${path}`;
}
export class Client {
constructor(private baseUrl: string) {}
fetch(path: string, options?: RequestInit) {
return fetch(getFullURL(this.baseUrl, path), options);
}
async stream(path: string, options?: StreamOptions) {
return nyreFetch.stream(getFullURL(this.baseUrl, path), options);
}
}
export default nyreFetch;
@nwaughachukwuma
Copy link
Author

Example

import nyreFetch from "./nyreFetch";

nyreFetch
  .get("https://example.com")
  .then((res) => res.json())
  .then((json) => console.log(json));

@nwaughachukwuma
Copy link
Author

This abstraction now has a home - https://github.com/nwaughachukwuma/nyre-fetch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment