ofetch-utils
v0.3.1
Published
Utility functions and hooks for ofetch to simplify URL template parameter binding and route parameter extraction
Maintainers
Readme
ofetch-utils
Utility functions and hooks for ofetch to simplify URL template parameter binding and route parameter extraction.
Features
- 🔗 URL Template Parameter Binding - Replace
{param}and:paramplaceholders with actual values - 🪝 ofetch Hook Integration - Seamless integration with ofetch's request/response lifecycle
- 🎯 Multiple Parameter Styles - Support for OpenAPI (
{param}) and H3/Express (:param) patterns - 🛡️ Type Safe - Full TypeScript support with comprehensive type definitions
- 🔄 Auto-detection - Automatically detect and handle different parameter styles
- 📦 Zero Dependencies - Lightweight with no external dependencies (except ofetch peer dependency)
- 🧪 Well Tested - Comprehensive test coverage for all functionality
Installation
# npm
npm install ofetch-utils
# yarn
yarn add ofetch-utils
# pnpm
pnpm add ofetch-utilsQuick Start
Basic URL Template Binding
import { bindUrlTemplateParams } from 'ofetch-utils'
// Replace parameters in URL templates
const url = bindUrlTemplateParams('/users/{userId}/posts/{postId}', {
userId: '123',
postId: 'hello-world'
})
// Result: '/users/123/posts/hello-world'ofetch Hook Integration
import { ofetch } from 'ofetch'
import { bindRequestParamsHook } from 'ofetch-utils'
// Create an ofetch client with automatic parameter binding
const client = ofetch.create({
onRequest: bindRequestParamsHook()
})
// Use template URLs directly in requests
const user = await client('/users/{userId}', {
params: { userId: '123' }
})
// Automatically requests: /users/123API Reference
bindUrlTemplateParams(templateUrl, pathParams, options?)
Replaces URL template parameters with actual values from an object.
Parameters:
templateUrl(string) - URL template with parameter placeholderspathParams(Record<string, any>) - Object containing parameter valuesoptions.mode?('auto' | 'openapi' | 'h3') - Parameter detection mode (default: 'auto')
Returns: string - URL with parameters replaced and properly encoded
Examples:
// OpenAPI style parameters
bindUrlTemplateParams('/api/{version}/users/{id}', {
version: 'v1',
id: 456
})
// Result: '/api/v1/users/456'
// H3/Express style parameters
bindUrlTemplateParams('/users/:userId/posts/:postId', {
userId: 'john',
postId: 'my-post'
})
// Result: '/users/john/posts/my-post'
// Mixed styles (auto-detection)
bindUrlTemplateParams('/api/{version}/users/:id', {
version: 'v2',
id: 'jane'
})
// Result: '/api/v2/users/jane'
// URL encoding of special characters
bindUrlTemplateParams('/search/{query}', {
query: 'hello world & more'
})
// Result: '/search/hello%20world%20%26%20more'extractRouteParamsFromQuery(url, options?)
Extracts route parameters from a URL and retrieves their values from query string or provided options.
Parameters:
url(string) - Complete URL with route pattern and optional query stringoptions.mode?('auto' | 'openapi' | 'h3') - Parameter detection modeoptions.params?(Record<string, any>) - Parameter values (highest priority)options.query?(Record<string, any>) - Query values (medium priority)
Returns: Record<string, string | undefined> - Object with parameter names and values
Examples:
// Extract from query string
extractRouteParamsFromQuery('/users/{userId}/posts/{postId}?userId=123&postId=456')
// Result: { userId: '123', postId: '456' }
// Use provided params
extractRouteParamsFromQuery('/users/{userId}', {
params: { userId: 123 }
})
// Result: { userId: '123' }
// Mixed parameter styles
extractRouteParamsFromQuery('/api/{version}/users/:userId', {
mode: 'auto',
query: { version: 'v1', userId: 'john' }
})
// Result: { version: 'v1', userId: 'john' }bindRequestParamsHook(options?)
Creates an ofetch hook that automatically binds URL template parameters from request options.
Parameters:
options.mode?('auto' | 'openapi' | 'h3') - Parameter detection mode (default: 'auto')
Returns: FetchHook - Hook function for use with ofetch
Examples:
import { ofetch } from 'ofetch'
import { bindRequestParamsHook } from 'ofetch-utils'
// Basic usage
const client = ofetch.create({
onRequest: bindRequestParamsHook()
})
await client('/users/{userId}/posts/{postId}', {
params: { userId: '123', postId: 'hello-world' }
})
// Requests: /users/123/posts/hello-world
// With specific mode
const apiClient = ofetch.create({
onRequest: bindRequestParamsHook({ mode: 'openapi' })
})
// Multiple hooks
const advancedClient = ofetch.create({
onRequest: [
bindRequestParamsHook(),
// other hooks...
]
})
// Works with different parameter styles
await client('/users/:userId/posts/{postId}', {
params: { userId: '123', postId: 'hello' }
})
// In auto mode, both :userId and {postId} are replacedParameter Detection Modes
auto (Default)
Automatically detects and processes both OpenAPI ({param}) and H3 (:param) style parameters.
'/api/{version}/users/:id' // Both {version} and :id are detectedopenapi
Only processes OpenAPI/Swagger style parameters ({param}).
'/api/{version}/users/{id}' // Only {version} and {id} are processed
'/api/{version}/users/:id' // Only {version} is processed, :id is ignoredh3
Only processes H3/Nuxt/Express style parameters (:param).
'/users/:userId/posts/:postId' // Only :userId and :postId are processed
'/users/{userId}/posts/:postId' // Only :postId is processed, {userId} is ignoredError Handling
The library provides clear error messages for common issues:
// Missing parameter
bindUrlTemplateParams('/users/{userId}', {})
// Throws: "Route parameter 'userId' not found in the provided object."
// Null/undefined values
bindUrlTemplateParams('/users/{userId}', { userId: null })
// Throws: "The value for the route parameter 'userId' cannot be null or undefined."Use Cases
REST API Clients
const apiClient = ofetch.create({
baseURL: 'https://api.example.com',
onRequest: bindRequestParamsHook()
})
// Clean, template-based API calls
await apiClient('/users/{userId}', { params: { userId: '123' } })
await apiClient('/posts/{postId}/comments', { params: { postId: '456' } })Dynamic Route Building
function buildRoute(template: string, params: Record<string, any>) {
return bindUrlTemplateParams(template, params)
}
const userProfileUrl = buildRoute('/users/{userId}/profile', { userId: 'john' })
const productUrl = buildRoute('/products/:category/:id', { category: 'electronics', id: '123' })URL Parameter Extraction
// Extract parameters from current route for API calls
const currentRoute = '/users/123/posts/456?sort=date'
const params = extractRouteParamsFromQuery(currentRoute)
// Use params for subsequent API callsTypeScript Support
Full TypeScript support with comprehensive type definitions:
import type {
BindRequestParamsHookOptions,
ExtractRouteParamsOptions,
RouteParamMode
} from 'ofetch-utils'
const mode: RouteParamMode = 'auto'
const options: BindRequestParamsHookOptions = { mode }Sponsors
License
MIT License © Eduardo Barros
