@rocketbase/commons-rest-client
v1.2.0
Published
Runtime library for @rocketbase OpenAPI generated TypeScript clients
Readme
@rocketbase/commons-rest-client
Runtime library for TypeScript clients generated by the @rocketbase OpenAPI generator.
Features
- 🔐 Authentication: React Context-based auth with Bearer token interceptor
- 🌐 Multi-Client Support: Named base URLs for multiple API endpoints
- 📄 Pagination: Helpers for React Query infinite queries
- 🎯 Type-Safe: Full TypeScript support with strict typing
- 📦 Tree-Shakeable: ESM and CJS builds with minimal bundle size
- ⚡ Modern: Built for axios 1.7+, React 18+, TypeScript 5+
Installation
npm install @rocketbase/commons-rest-client axios reactPeer Dependencies
axios>= 1.7.0react>= 18.0.0
Usage
Basic Setup (Single API)
import { AuthProvider, type TokenService } from '@rocketbase/commons-rest-client';
// Implement your token service
const tokenService: TokenService = {
isLoggedIn: () => !!localStorage.getItem('token'),
token: () => localStorage.getItem('token'),
updateToken: async () => {
// Optional: refresh token logic
const newToken = await refreshToken();
localStorage.setItem('token', newToken);
return newToken;
},
};
// Wrap your app
function App() {
return (
<AuthProvider
tokenService={tokenService}
baseUrl="https://api.example.com"
>
<YourApp />
</AuthProvider>
);
}Multi-Client Setup (Multiple APIs)
import { AuthProvider } from '@rocketbase/commons-rest-client';
function App() {
return (
<AuthProvider
tokenService={tokenService}
baseUrl={{
main: 'https://api.example.com',
auth: 'https://auth.example.com',
analytics: 'https://analytics.example.com',
}}
>
<YourApp />
</AuthProvider>
);
}Using Generated Clients
import { useAuth } from '@rocketbase/commons-rest-client';
import { createMainApi, createAuthApi } from './generated/client';
function MyComponent() {
const { axiosClient, baseUrl } = useAuth();
// Single API
const api = createMainApi(axiosClient, { baseURL: baseUrl() });
// Multiple APIs with named base URLs
const mainApi = createMainApi(axiosClient, { baseURL: baseUrl('main') });
const authApi = createAuthApi(axiosClient, { baseURL: baseUrl('auth') });
// Use the API
const data = await api.users.getUser({ id: '123' });
}Custom Axios Configuration
<AuthProvider
tokenService={tokenService}
baseUrl="https://api.example.com"
axiosConfigure={(instance) => {
instance.defaults.timeout = 5000;
instance.defaults.headers.common['X-Custom-Header'] = 'value';
}}
>
<YourApp />
</AuthProvider>Using Pagination Utilities
import { useInfiniteQuery } from '@tanstack/react-query';
import { createPaginationOptions, infiniteTotalElements } from '@rocketbase/commons-rest-client';
function UserList() {
const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
queryKey: ['users'],
queryFn: ({ pageParam = 0 }) => api.users.list({ page: pageParam, size: 20 }),
...createPaginationOptions(),
});
const totalUsers = infiniteTotalElements(data);
return (
<div>
<p>Total users: {totalUsers}</p>
{data?.pages.map((page) =>
page.content.map((user) => <UserCard key={user.id} user={user} />)
)}
{hasNextPage && <button onClick={() => fetchNextPage()}>Load More</button>}
</div>
);
}API Reference
AuthProvider
React component that provides authentication context.
Props:
tokenService: TokenService- Token service implementationbaseUrl: string | Record<string, string>- API base URL(s)axiosConfigure?: (instance: AxiosInstance) => void- Optional axios configurationchildren: ReactNode- Child components
useAuth()
Hook to access authentication context. Must be used within AuthProvider.
Returns:
axiosClient: AxiosInstance- Configured axios instance with auth interceptorbaseUrl: (key?: string) => string- Base URL resolvertokenService: TokenService- Token service instance
TokenService
Interface for managing authentication tokens.
interface TokenService {
isLoggedIn: () => boolean;
token: () => string | null;
updateToken?: () => Promise<string>;
}PageableResult
Standard pageable result wrapper for REST APIs.
interface PageableResult<T> {
content: T[];
totalElements: number;
totalPages: number;
page: number;
pageSize: number;
}createPaginationOptions()
Creates pagination options for React Query infinite queries.
Returns:
getPreviousPageParam- Function to get previous page numbergetNextPageParam- Function to get next page numberinitialPageParam- Initial page number (0)
infiniteTotalElements(data)
Extracts total element count from infinite query data.
Parameters:
data: InfiniteData<PageableResult<T>> | undefined- React Query infinite data
Returns: number - Total number of elements across all pages
buildRequestorFactory()
Creates a requestor factory for building type-safe API client functions.
const builder = buildRequestorFactory(axiosClient, { baseURL: 'https://api.example.com' });
const getUser = builder<{ id: string }, User>({
method: 'get',
url: ({ id }) => `/users/${id}`,
});
const user = await getUser({ id: '123' });Development
Build
cd typescript-runtime
npm install
npm run buildOutput files:
dist/index.mjs- ESM builddist/index.cjs- CommonJS builddist/index.d.ts- TypeScript type definitions
Testing
npm run testType Checking
npm run typecheckLicense
MIT
Author
rocketbase.io
