http-service-router
This is a super tiny router to be used in a microservice-like environment. It parses a given URL and returns a matching object. It also calculates the URL with the part for the match stripped. This is very powerful when being combined with express's path-to-regexp.
Setup
$ npm i http-service-router
Contribute
Pull-requests are always welcome. For any problems or questions just open an issue.
Usage
Simple
The following example shows the simplest use case for the router. Keep reading for more advanced and powerful use-cases:
const createRouter = const router = const srv = http { // ... Do your magic}
Advanced use-case
In the following example I'll show you how the router can be utilized to build up a powerful chain of microservices that communicate using a proxy mechanism. This uses the http-proxy module and the expression building module path-to-regexp.
const http = const createRouter = const httpProxy = const p = const api = httpProxyconst app = httpProxyconst router = const srv = http
Now api
and app
can again use the router to dispatch to more nested microservice.
Modular monolith
Sometimes we just don't have the ability to design our application with multiple processes in mind. Maybe we're just starting off and want to deploy the application using a hobby dyno on heroku. But this doesn't disable us to design a modular application which can be easily converted to a microservice-like architecture. I like to use micro to build such applications.
Frontend service (server.js)
const createRouter = const createAuth = const createAPI = const createApp = /* ... */ moduleexports = { const router = return { const r = router if r requrl = rurl return r else }}
Auth service (auth.js)
const createError = moduleexports = createAuth { return { // ... Do authentication logic (e.g. JSON-Web-Token) ... const user = if !user throw reqheaders'x-user' = user_id return }}
Api service (api.js)
moduleexports = createAPI { return { // Do API stuff and use `req.headers['x-user']` as user id. }}
This is a nice modular architecture which can be executed using micro server.js
. And the best
thing is that you can easily convert it to a microservice architecture using the http-proxy
approach
described above. But it gives you the chance to start-out in a lean fashion without thinking about
scaling too much.
Cheers!