Utility functions and hooks for ofetch to simplify URL template parameter binding and route parameter extraction
npm install ofetch-utils[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![bundle][bundle-src]][bundle-href]
[![JSDocs][jsdocs-src]][jsdocs-href]
[![License][license-src]][license-href]
Utility functions and hooks for ofetch to simplify URL template parameter binding and route parameter extraction.
- ๐ URL Template Parameter Binding - Replace {param} and :param placeholders 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
``bashnpm
npm install ofetch-utils
Quick Start
$3
`typescript
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'
`$3
`typescript
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/123
`API Reference
$3
Replaces URL template parameters with actual values from an object.
Parameters:
-
templateUrl (string) - URL template with parameter placeholders
- pathParams (Record) - Object containing parameter values
- options.mode? ('auto' | 'openapi' | 'h3') - Parameter detection mode (default: 'auto')Returns:
string - URL with parameters replaced and properly encodedExamples:
`typescript
// 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'
`$3
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 string
- options.mode? ('auto' | 'openapi' | 'h3') - Parameter detection mode
- options.params? (Record) - Parameter values (highest priority)
- options.query? (Record) - Query values (medium priority)Returns:
Record - Object with parameter names and valuesExamples:
`typescript
// 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' }
`$3
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 ofetchExamples:
`typescript
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 replaced
`Parameter Detection Modes
$3
Automatically detects and processes both OpenAPI ({param}) and H3 (:param) style parameters.`typescript
'/api/{version}/users/:id' // Both {version} and :id are detected
`$3
Only processes OpenAPI/Swagger style parameters ({param}).`typescript
'/api/{version}/users/{id}' // Only {version} and {id} are processed
'/api/{version}/users/:id' // Only {version} is processed, :id is ignored
`$3
Only processes H3/Nuxt/Express style parameters (:param).`typescript
'/users/:userId/posts/:postId' // Only :userId and :postId are processed
'/users/{userId}/posts/:postId' // Only :postId is processed, {userId} is ignored
`Error Handling
The library provides clear error messages for common issues:
`typescript
// 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
$3
`typescript
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' } })
`$3
`typescript
function buildRoute(template: string, params: Record) {
return bindUrlTemplateParams(template, params)
}const userProfileUrl = buildRoute('/users/{userId}/profile', { userId: 'john' })
const productUrl = buildRoute('/products/:category/:id', { category: 'electronics', id: '123' })
`$3
`typescript
// 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 calls
`TypeScript Support
Full TypeScript support with comprehensive type definitions:
`typescript
import type {
BindRequestParamsHookOptions,
ExtractRouteParamsOptions,
RouteParamMode
} from 'ofetch-utils'const mode: RouteParamMode = 'auto'
const options: BindRequestParamsHookOptions = { mode }
``MIT License ยฉ Eduardo Barros
[npm-version-src]: https://img.shields.io/npm/v/ofetch-utils?style=flat&colorA=080f12&colorB=1fa669
[npm-version-href]: https://npmjs.com/package/ofetch-utils
[npm-downloads-src]: https://img.shields.io/npm/dm/ofetch-utils?style=flat&colorA=080f12&colorB=1fa669
[npm-downloads-href]: https://npmjs.com/package/ofetch-utils
[bundle-src]: https://img.shields.io/bundlephobia/minzip/ofetch-utils?style=flat&colorA=080f12&colorB=1fa669&label=minzip
[bundle-href]: https://bundlephobia.com/result?p=ofetch-utils
[license-src]: https://img.shields.io/github/license/dbarjs/ofetch-utils.svg?style=flat&colorA=080f12&colorB=1fa669
[license-href]: https://github.com/dbarjs/ofetch-utils/blob/main/LICENSE
[jsdocs-src]: https://img.shields.io/badge/jsdocs-reference-080f12?style=flat&colorA=080f12&colorB=1fa669
[jsdocs-href]: https://www.jsdocs.io/package/ofetch-utils