Helpers for creating route paths from the api to the client
pnpm i @andremalveira/route
Add dynamic parameters and query parameters in the path
- param:
path
- return:
function(ParamValue | Object(ParamValue), Object?(QueryValue))
Recognized parameter key format::key
|{key}
|[key]
// routes/api.routes.ts
import { param } from '@andremalveira/route';
const routes = {
user: param('/user/:userId')
}
export default routes
// How to use
import routes from 'routes/api.routes';
const userId = 032;
routes.user(userId); // /user/032
// Type
param<ParamKeys, QueryKeys>('/path') => (paramKeys, queryKeys) => string
//Example
param<'userId'>('/user')
Add query parameters in path
- param:
path
- return:
function(Object?(QueryValue))
// routes/api.routes.ts
import { query } from '@andremalveira/route';
const routes = {
posts: query('/posts')
}
export default routes
// How to use
import routes from 'routes/api.routes';
routes.posts({ category: 'movies', type:'science-fiction' }); // /posts?category=movies&type=science-fiction
// Type
query<QueryKeys>('/path') => (queryKeys?) => string
//Example
query<'category' | 'type'>('/posts')
Creates a group of routes based on the options
- param_1:
Object(options)
|{}
| null
prefix?
: prefix for route path
namespace?
: returns the routes inside a new object called 'namespace'
baseUrl?
: url base from path
- param_2:
Object(routes)
- return:
Object(routes)
// routes/api.routes.ts
import { group } from '@andremalveira/route';
const routes = {
post: group({ prefix: '/post' }, {
add: '/add',
update: param('/update/:postId'),
delete: param('/delete/:postId'),
})
}
export default routes
// How to use
import routes from 'routes/api.routes';
const postId = 12;
routes.post.add // /post/add
routes.post.update(postId) // /post/update/12
routes.post.delete(postId) // /post/delete/12
group({
prefix?: string,
baseUrl?: string
namespace?: string,
}, routes ) => routes
Returns formatted path segment
- param_1:
string[]
: url segment- param_2:
object
: query keys- return:
string
import { path } from '@andremalveira/route';
const newPath = path(['api', 'user', 'posts'], { status: true }) // api/user/posts?status=true
path(string[], object) => string