npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

feature-fetch

v0.0.33

Published

Straightforward, typesafe, and feature-based fetch wrapper supporting OpenAPI types

Downloads

1,681

Readme

Status: Experimental

feature-fetch is a straightforward, typesafe, and feature-based fetch wrapper supporting OpenAPI types.

  • Lightweight & Tree Shakable: Function-based and modular design (< 6KB minified)
  • Fast: Thin wrapper around the native fetch, maintaining near-native performance
  • Modular & Extendable: Easily extendable with features like withRetry(), withOpenApi(), ..
  • Typesafe: Build with TypeScript for strong type safety and support for openapi-typescript types
  • Standalone: Only dependent on fetch, ensuring ease of use in various environments

📚 Examples

🌟 Motivation

Create a typesafe, straightforward, and lightweight fetch wrapper that seamlessly integrates with OpenAPI schemas using openapi-typescript. It aims to simplify error handling by returning results in a predictable manner with ts-results-es. Additionally, it is designed to be modular & extendable, enabling the creation of straightforward API wrappers, such as for the Google Web Fonts API (see google-webfonts-client). feature-fetch only depends on fetch, making it usable in most sandboxed environments like Figma plugins.

⚖️ Alternatives

📖 Usage

import { createApiFetchClient } from 'feature-fetch';

const fetchClient = createApiFetchClient({
	prefixUrl: 'https://api.example.com/v1'
});

// Send request
const response = await fetchClient.get<{ id: string }>('/blogposts/{postId}', {
	pathParams: {
		postId: '123'
	}
});

// Handle response
if (response.isOk()) {
	console.log(response.value.data); // Handle successful response
} else {
	console.error(response.error.message); // Handle error response or network exception
}

// Or unwrap the response, throwing an exception on error
try {
	const data = response.unwrap().data;
	console.log(data);
} catch (error) {
	console.error(error.message);
}

withApi()

Enhance feature-fetch to create a typesafe fetch wrapper. This feature provides common HTTP methods (get, post, put, del) ensuring requests and responses are typed.

  1. Create an API Fetch Client: Use createApiFetchClient to create a fetch client with a specified base URL.

    import { createApiFetchClient } from 'feature-fetch';
    
    const fetchClient = createApiFetchClient({
    	prefixUrl: 'https://api.example.com/v1'
    });
  2. Send Requests: Use the fetch client to send requests, specifying the response type for better type safety.

    // Send request
    const response = await fetchClient.get<{ id: string }>('/blogposts/{postId}', {
    	pathParams: {
    		postId: '123'
    	}
    });

withOpenApi()

Enhance feature-fetch with OpenAPI support to create a typesafe fetch wrapper. This feature provides common HTTP methods (get, post, put, del) that are fully typed by leveraging your OpenAPI schema using openapi-typescript.

  1. Generate TypeScript Definitions: Use openapi-typescript to generate TypeScript definitions from your OpenAPI schema.

    npx openapi-typescript ./path/to/my/schema.yaml -o ./path/to/my/schema.d.ts

    More info

  2. Create an OpenAPI Fetch Client: Import the generated paths and use createOpenApiFetchClient() to create a fetch client.

    import { createOpenApiFetchClient } from 'feature-fetch';
    import { paths } from './openapi-paths';
    
    const fetchClient = createOpenApiFetchClient<paths>({
    	prefixUrl: 'https://api.example.com/v1'
    });
  3. Send Requests: Use the fetch client to send requests, ensuring typesafe parameters and responses.

    // Send request
    const response = await fetchClient.get('/blogposts/{postId}', {
    	pathParams: {
    		postId: '123'
    	}
    });

withGraphQL()

Enhance feature-fetch to create a typesafe fetch wrapper specifically for GraphQL requests. This feature allows you to send GraphQL queries and mutations, ensuring requests and responses are typed.

  1. Create a GraphQL Fetch Client: Use withGraphQL to extend your existing fetch client with GraphQL capabilities.

    import { gql, withGraphQL } from 'feature-fetch';
    import createFetchClient from './createFetchClient';
    
    const baseFetchClient = createFetchClient({
    	prefixUrl: 'https://api.example.com/v1/graphql'
    });
    
    const graphqlClient = withGraphQL(baseFetchClient);
  2. Define GraphQL Queries: Use the gql tagged template literal to define your GraphQL queries with syntax highlighting.

    const GET_USER = gql`
    	query GetUser($id: ID!) {
    		user(id: $id) {
    			id
    			name
    			email
    		}
    	}
    `;
  3. Send GraphQL Requests: Use the GraphQL-enabled fetch client to send requests, specifying the response type for better type safety.

    // Send GraphQL query
    const response = await graphqlClient.query<
    	{ id: number },
    	{ user: { id: string; name: string; email: string } }
    >(GET_USER, {
    	variables: {
    		id: '123'
    	}
    });

🚨 Errors

When handling API error responses (response.isErr()), response can be one of three Error types, each representing a different kind of failure.

NetworkError (extends FetchError)

Indicates a failure in network communication, such as loss of connectivity.

if (response.isErr() && response.error instanceof NetworkError) {
	console.error('Network error:', response.error.message);
}

RequestError (extends FetchError)

Occurs when the server returns a response with a status code indicating an error (e.g., 4xx or 5xx).

if (response.isErr() && response.error instanceof RequestError) {
	console.error('Request error:', response.error.message, 'Status:', response.error.status);
}

FetchError

A general exception type that can encompass other error scenarios not covered by NetworkError or RequestError, for example when the response couldn't be parsed, ..

if (response.isErr() && response.error instanceof FetchError) {
	console.error('Service error:', response.error.message);
}

Example

if (response.isErr()) {
	const error = response.error;

	if (isStatusCode(error, 404)) {
		console.error('Not found:', error.data);
	}

	if (error instanceof NetworkError) {
		console.error('Network error:', error.message);
	} else if (error instanceof RequestError) {
		console.error('Request error:', error.message, 'Status:', error.status);
	} else if (error instanceof FetchError) {
		console.error('Service error:', error.message);
	} else {
		console.error('Unexpected error:', error);
	}
}

📙 Features

withRetry()

Retries each request using an exponential backoff strategy if a network exceptions (NetworkError) or HTTP 429 (Too Many Requests) response occur.

import { createApiFetchClient, withRetry } from 'feature-fetch';

const fetchClient = withRetry(
	createApiFetchClient({
		prefixUrl: 'https://api.example.com/v1'
	}),
	{
		maxRetries: 3
	}
);
  • maxRetries: Maximum number of retry attempts

withDelay()

Delays each request by a specified number of milliseconds before sending it.

import { createApiFetchClient, withDelay } from 'feature-fetch';

const fetchClient = withDelay(
	createApiFetchClient({
		prefixUrl: 'https://api.example.com/v1'
	}),
	1000
);
  • delayInMs: Delay duration in milliseconds

❓ FAQ

Why is @0no-co/graphql.web a dependency if it's not always used?

@0no-co/graphql.web is listed as a dependency because it's dynamically imported in the getQueryString() function. If the function isn’t used, Webpack's tree shaking should exclude it from the final bundle. This ensures that only necessary modules are included, keeping your build clean.