🚉 Micro Router - A tiny and functional router for ZEIT's micro
👌 Features
- Tiny. Just couple lines of code.
- Functional. Write your http methods using functions.
- Async. Design to use with
async/await
💻 Usage
Install as project dependency:
$ yarn add microrouter
Then you can define your routes inside your microservice:
const send = const router get = const hello = const notfound = moduleexports =
async/await
You can use your handler as an async function:
const send = const router get = const hello = async moduleexports =
route methods
Each route is a single basic http method that you import from microrouter
and has the same arguments:
get(path = String, handler = Function)
post(path = String, handler = Function)
put(path = String, handler = Function)
patch(path = String, handler = Function)
del(path = String, handler = Function)
head(path = String, handler = Function)
options(path = String, handler = Function)
path
A simple url pattern that you can define your path. In this path you can set your parameters using a :
notation. The req
parameter from handler
will return this parameters as an object.
For more information about how you can define your path, see url-pattern that's the package that we're using to match paths.
handler
The handler
method is a simple function that will make some action base on your path.
The format of this function is (req, res) => {}
req.params
As you can see below, the req
parameter has a property called params
that represents the parameters defined in your path
:
const router get = const request = // service.jsmoduleexports = // test.jsconst response = await console // { who: 'World' }
req.query
The req
parameter also has a query
property that represents the queries
defined in your requision url:
const router get = const request = // service.jsmoduleexports = // test.jsconst response = await console // { id: 1 }
Parsing Body
By default, router doens't parse anything from your requisition, it's just match your paths and execute a specific handler. So, if you want to parse your body requisition you can do something like that:
const router post = const json send = const request = // service.jsconst user = async { const body = await } moduleexports = // test.jsconst body = id: 1 const response = await request
UrlPattern instance as path
The package url-pattern has a lot of options inside it to match url. If you has a different need for some of your paths, like make pattern from a regexp, you can pass a instance of UrlPattern
as the path parameter:
const UrlPattern = const router get = const routes =
Namespaced Routes
If you want to create nested routes, you can define a namespace for your routes using the withNamespace
high order function:
const withNamespace router get = const json send = const oldApi = const newApi = const routes =
PS: The nested routes doesn't work if you pass a UrlPattern instance as path argument!