routeGen
Define your API and SPA routes in one place. Use them anywhere.
The Problem
Defining your routes as "magic strings" is messy never a good idea, especially as your app grows. You might have something like this:
// foo.jshttphttp // and then again in bar.jshttphttp
And what if you decide to change your routes? You need to update them all over the place. What if you mistype a route in one place? It can break things and get messy. routeGen
fixes all these issues.
The Solution / Basic Usage
Rather than have the "magic strings" all over the place, you can define them in one place and use them everywhere. Need to inerpolate a value into a url? No problem. You can even disable redefining routes after they're exported with the magic lock()
method. Grouping certain routes with a prefix and namespace is a breeze with the prefix()
method. routeGen
is simple, useful and incredibly lightweight at only 1.6kb.
// routes.js; // all routes will be prefixed with the baseUrlconst routes = ; routes; routes; ;
// some-other-file.js;; http; // POST => http://myapi.test/api/auth/loginhttp; // GET => http://myapi.test/api/user/1
An example with axios
;; axios; // POST => http://myapi.test/api/auth/loginaxios; // GET => http://myapi.test/api/user/1
Installation
npm i routegen --save
API
routeGen({...})
To define sets of routes, simply call import routegen
and call it as a function. The only parameter it accepts is an object with a baseUrl
.
; const routes = ;
You may also define multiple sets of routes:
; const apiRoutes = ; const spaRoutes = ;
set(key, value)
Pretty straight forward. Set a new route.
routes;routes;
generate(key, params = {})
Retrieve a value from the routes.
const routes = ; routes; routes; // => /foo/bar
Some routes require an interpolated value. For instance, getting a user by id. You can define a route that accepts params and retrieve it with generate()
.
const routes = ; routes; routes; // GET => /user/1
lock()
If you'd like to define your routes in one place and disallow setting any new routes once exported, you may call the lock()
method.
const routes = ; routes;routes; ;
Calling lock()
returns an api with access only to generate()
, and all()
. So, the above example could not be modified once imported.
prefix({ path, name })
You may have times where you want to prefix routes with a namespace and/or a path. prefix()
allows for just that.
; const routes = ; routesprefix path: '/auth' name: 'auth' login: '/login' logout: '/logout' register: '/register'; routes // /auth/loginroutes // /auth/logoutroutes // /auth/register
all()
If you need a way to retrieve all the routes at once, you may call all()
.
routesall