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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@ryzes/rio

v0.0.8

Published

Axios wrapper for handling { code, message, data } responses and integrating with TanStack React Query.

Readme

@ryzes/rio - Axios Wrapper for Standardized API Responses

⚠️ IMPORTANT: This library does not support HTTP status code 3xx redirects. Only 2xx success responses and 4xx/5xx error responses are properly handled.

Overview

Rio is a TypeScript library that provides an Axios wrapper for handling standardized { code, message, data } API responses and integrates seamlessly with TanStack React Query.

Installation

pnpm add @ryzes/rio
# or with npm
npm install @ryzes/rio
# or with yarn
yarn add @ryzes/rio

Quick Start

1. Initialize HTTP Client

import { httpClient } from '@ryzes/rio';

httpClient.initialize({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  successCode: 0,
});

2. Use with React Query

import { QueryClientProvider } from '@tanstack/react-query';
import { createRioQueryClient } from '@ryzes/rio';
import { httpClient } from '@ryzes/rio';

// Initialize HTTP client
httpClient.initialize({
  baseURL: 'https://api.example.com'
});

// Create React Query client with error handling
const queryClient = createRioQueryClient((title: string, info: string) => {
  // Handle errors globally
  console.error('Error:', title, info);
});

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your app components */}
    </QueryClientProvider>
  );
}

3. Make HTTP Requests

import { useQuery } from '@tanstack/react-query';
import { httpClient } from '@ryzes/rio';

// In your React component
const MyComponent = () => {
  const { data, isLoading, error } = useQuery({
    queryKey: ['userData'],
    queryFn: async () => {
      // Directly use httpClient.get()
      return httpClient.get<{ name: string; age: number }>('/users/1');
    },
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {(error as Error).message}</div>;

  return <div>Hello, {data?.name}!</div>;
};

// Custom error handling with skipGlobalError
const MyComponentWithCustomErrorHandling = () => {
  const { data, isLoading, error } = useQuery({
    queryKey: ['userData'],
    queryFn: async () => {
      // Skip global error handling to handle errors yourself
      return httpClient.get('/users/1', { meta: { skipGlobalError: true } });
    },
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) {
    // Handle error yourself instead of using global error handler
    return <div>Custom error message: {(error as Error).message}</div>;
  }

  return <div>Hello, {data?.name}!</div>;
};

4. Authentication Support

import { ConsoleAuthService } from '@ryzes/rio';

// Initialize with authentication service
httpClient.initialize({
  baseURL: 'https://api.example.com',
  authService: new ConsoleAuthService(),
});

// Login and token handling
interface LoginResponse {
  token: string;
}

const loginResponse = await httpClient.post<LoginResponse>('/auth/login', {
  username: 'your-username',
  password: 'your-password'
});

// Set the authentication token
httpClient.setAuthToken(loginResponse.token);

// Get the current token
const currentToken = httpClient.getAuthToken();

// Clear the token
httpClient.clearAuthToken();

API Reference

Exported Functions

  • httpClient - Pre-configured HTTP client instance
  • createRioQueryClient(errorReporter: (title: string, info: string) => void) - Creates React Query client with built-in error handling

HttpClient Methods

The httpClient instance provides the following HTTP methods:

  • get(url: string, config?: AxiosRequestConfig) - GET request
  • post(url: string, data: any, config?: AxiosRequestConfig) - POST request
  • put(url: string, data: any, config?: AxiosRequestConfig) - PUT request
  • patch(url: string, data: any, config?: AxiosRequestConfig) - PATCH request
  • delete(url: string, config?: AxiosRequestConfig) - DELETE request

Authentication Methods

  • setAuthToken(token: string) - Set authentication token
  • getAuthToken(): string | null - Get current authentication token
  • clearAuthToken() - Clear authentication token

Raw Response Methods

The library also provides raw response methods that return the complete { code, message, data } structure:

  • getRaw(url: string, config?: AxiosRequestConfig) - GET request returning raw response
  • postRaw(url: string, data: any, config?: AxiosRequestConfig) - POST request returning raw response
  • putRaw(url: string, data: any, config?: AxiosRequestConfig) - PUT request returning raw response
  • patchRaw(url: string, data: any, config?: AxiosRequestConfig) - PATCH request returning raw response
  • deleteRaw(url: string, config?: AxiosRequestConfig) - DELETE request returning raw response

Common Usage Examples

Simple GET Request

const result = await httpClient.get('/api/users');

GET Request with Raw Response

const rawResponse = await httpClient.getRaw<{ name: string; age: number }>('/api/users/1');
// rawResponse will be: { code: 0, message: 'success', data: { name: 'John', age: 30 } }

// Example with server returning {code:200,message:"ok",data:{result:true}}
const rawResponse = await httpClient.getRaw('/api/example');
// Returns: { code: 200, message: "ok", data: { result: true } }

POST Request with Data

const newUser = await httpClient.post('/api/users', {
  name: 'John Doe',
  email: '[email protected]'
});

POST Request with Raw Response

const rawResponse = await httpClient.postRaw('/api/users', {
  name: 'John Doe',
  email: '[email protected]'
});
// rawResponse will be: { code: 0, message: 'success', data: { id: 1, name: 'John', email: '[email protected]' } }

Regular Methods vs Raw Methods

Regular methods (get, post, put, patch, delete) return only the data field from the response:

// Server returns: {code:200, message:"ok", data:{result:true}}
const result = await httpClient.get('/api/example');
// Returns: {result: true} (only the data field)

Raw methods (getRaw, postRaw, putRaw, patchRaw, deleteRaw) return the complete response structure:

// Server returns: {code:200, message:"ok", data:{result:true}}
const rawResult = await httpClient.getRaw('/api/example');
// Returns: {code: 200, message: "ok", data: {result: true}} (complete response)

Request with Query Parameters

const users = await httpClient.get('/api/users', {
  params: { page: 1, limit: 10 }
});

Login and Authentication

// Login
const response = await httpClient.post('/auth/login', {
  username: 'testuser',
  password: 'password123'
});

// Set token for future requests
httpClient.setAuthToken(response.token);

Authentication Services

The library supports different authentication service implementations:

  • ConsoleAuthService - For server-side rendering/console applications (stores tokens in memory)
  • DefaultAuthService - For browser applications (stores tokens in localStorage)
  • Custom services implementing the AuthService interface

Advanced Usage

Custom Success Code

// If your API uses 200 instead of 0 for success
httpClient.initialize({
  baseURL: 'https://api.example.com',
  successCode: 200,
});

Error Handling Integration

import { toast } from 'sonner';

const queryClient = createRioQueryClient((title: string, info: string) => {
  toast.error(info); // Show toast notification for errors
});

License

MIT © Ryzes