npm.io
4.0.0 • Published 1 week ago

@sapphire/fetch

Licence
MIT
Version
4.0.0
Deps
0
Size
89 kB
Vulns
0
Weekly
0
Stars
192

Sapphire Logo

@sapphire/fetch

Tiny wrapper around Node's global fetch for improved TypeScript and data type support

GitHub npm bundle size npm

Table of Contents

Description

Node has a great global fetch (powered by undici) for making API calls, but because it focuses solely on bringing the Fetch API to Node.js, it doesn't provide specific error messages and handling for different return types (JSON, Buffer, plain text, etc). This is where @sapphire/fetch comes in. The syntax is more restrictive than that of undici, but that makes it consistent and easier to use in TypeScript.

Features

  • Wraps global fetch with helpers for JSON, text, and binary response data
  • Exported enum for the common return data types
  • Provides typed JSON responses and serializes plain-object request bodies
  • Throws a descriptive error when a response has a non-success status
  • Uses the platform's global Fetch API implementation

Installation

You can use the following command to install this package, or replace npm install with your package manager of choice.

npm install @sapphire/fetch

TypeScript configuration

When using @sapphire/fetch with TypeScript, include dom in the lib option of your tsconfig.json. The package uses Fetch API types such as RequestInit and Response.

{
	"compilerOptions": {
		"lib": ["ES2022", "dom"]
	}
}

Usage

When providing a serializable object to the body option, @sapphire/fetch will automatically call JSON.stringify on the object. This means you can pass an object directly to the body option without having to call JSON.stringify yourself. If the body is not serializable (such as a File, Buffer, or Blob), the body will be sent as-is. Serializability is calculated based on:

  • If the body is null
  • If the body's .constructor property is undefined
  • If the body's .constructor.name property is Object
  • If the body has a function property named toJSON

Because @sapphire/fetch aims to be as close to global fetch as possible, it doesn't support proxy options that a library like undici does. If you want to use a proxy, you should use undici directly.

GETting JSON data
// Import the fetch function
import { fetch, FetchResultTypes } from '@sapphire/fetch';

interface JsonPlaceholderResponse {
	userId: number;
	id: number;
	title: string;
	completed: boolean;
}

// Fetch the data. No need to call `.json()` after making the request!
const data = await fetch<JsonPlaceholderResponse>('https://jsonplaceholder.typicode.com/todos/1', FetchResultTypes.JSON);

// Do something with the data
console.log(data.userId);
GETting Buffer data (images, etc.)
// Import the fetch function
import { fetch, FetchResultTypes } from '@sapphire/fetch';

// Fetch the data. No need to call `.buffer()` after making the request!
const sapphireLogo = await fetch('https://github.com/sapphiredev.png', FetchResultTypes.Buffer);

// sapphireLogo is the `Buffer` of the image
console.log(sapphireLogo);
POSTing JSON data
// Import the fetch function
import { fetch, FetchResultTypes, FetchMethods } from '@sapphire/fetch';

// Post the data. No need to call `.json()` after making the request!
const responseData = await fetch(
	'https://jsonplaceholder.typicode.com/todos',
	{
		method: FetchMethods.Post,
		headers: {
			'Content-Type': 'application/json'
		},
		body: { name: 'John Doe' }
	},
	FetchResultTypes.JSON
);

// Do something with the response data
console.log(responseData);

Buy us some doughnuts

Sapphire Community is and always will be open source, even if we don't get donations. That being said, we know there are amazing people who may still want to donate just to show their appreciation. Thank you very much in advance!

We accept donations through Open Collective, Ko-fi, PayPal, Patreon and GitHub Sponsorships. You can use the buttons below to donate through your method of choice.

Donate With Address
Open Collective Click Here
Ko-fi Click Here
Patreon Click Here
PayPal Click Here

Contributors

Please make sure to read the Contributing Guide before making a pull request.

Thank you to all the people who already contributed to Sapphire!

Keywords