micro-rest-fs
v0.0.4
Published
Tiny path based rest router for zeit's micro
Downloads
2
Maintainers
Readme
micro-rest-fs
Tiny path based rest router for micro styled after next.js path based routing.
- no config
- parameterized paths
- query string
usage
Assuming your have a micro server serving index.js
, you can use the router like this
const micro = require('micro')
const match = require('micro-rest-fs')(__dirname)
const server = micro((req, res) => {
const matched = match(req)
if (matched) return matched(req, res)
micro.send(res, 404, { error: 'Not found' })
})
server.listen(8080)
Full demo can be found in demo/simple and run with npm run demo-simple
This will allow you to create files within the api
folder that map to api paths, so assuming a structure like this
demo/simple
├── api
│ ├── :echo
│ │ └── index.js
│ └── random
│ └── get.js
└── index.js
The following routes will be generated
/api/random
/
/api/:echo
The routes are sorted so that exact matches are before paramaterised matches, and specific http methods are before the general index.js
handlers. Each request is handled by the first matched route.
Each route is configured to expect a function, which will be called with req
and res
including req.params
, and req.query
decorations
For example, if demo/simple/api/random/get.js
looks like this
const { send } = require('micro')
module.exports = (req, res) => send(res, 200, Math.random().toString())
The api call and response will look like this
fetch('/api/random')
// => 0.006965265801673448
And where the demo/simple/api/echo/index.js
file looks like this
const { send } = require('micro')
module.exports = (req, res) => send(res, 200, {method: req.method, params: req.params, query: req.query})
The call and response could look like this
fetch('/api/anything?foo=bar&baz')
// => {"method":"GET","params":{"echo":"anything"},"query":{"foo":"bar","baz":""}}
Notice the fetched url is /api/anything
and is matched by the /api/:echo
, and the echo
param is set to the route value dynamically.
The echo route will also handle calls from unhandled http methods to /api/random
which only has a GET
handler based on the filename of demo/simple/api/random/get.js
fetch('/api/random?this=that', {method: 'post'})
// => {"method":"POST","params":{"echo":"random"},"query":{"this":"that"}}
Works fine with async
and await
module.exports = async (req, res) => {
const data = await fetch('http://example.com/api/something')
send(res, 200, data)
}
If you need to control to sorting order of routes, you can pass a sort function as a config paramater, for example to give presedence to paramaterised routes over exactly matched routes you could do something like this
const match = require('micro-rest-fs')(__dirname, {sort: (a, b) => a.params.length ? -1 : 1})