Releasing @clarityhub/serverless-simple-router

Ivan Montiel
2 min readDec 19, 2020

As part of my on-going efforts to continue to contribute to the open source community, I have released @clarityhub/serverless-simple-router as part of the

open source ecosystem.

What’s It For?

At Clarity Hub, we use serverless to quickly build new features and deploy without the overhead of configuring servers using kubernetes or docker. This package lets us quickly route incoming requests to controllers so that our code can stay organized within a serverless lambda.

Usage

All of the documentation on how to use the serverless-simple-router can be found in the README of the Github repo, but to give a quick overview: if you map a set of http paths from your serverless.yml file to a single handler, the serverless-simple-router can be used to parse the incoming request to the right controller method.

Example serverless.yml configuration:

service: example
provider:
name: aws
runtime: nodejs12.x
functions:
root:
handler: src/router.default
events:
- http:
path: /
method: any
cors: true
- http:
path: /{proxy+}
method: any
cors: true

Once the http paths are configured to route to the router.js file, you can use the serverless-simple-router:

import { Router, RouteBuilder } from '@clarityhub/serverless-simple-router';
import TaskController from './controllers/TaskController';

const middyMiddleware = [httpHeaderNormalizer(), cors(), bodyParser()];
routes.resource('/tasks', RouteBuilder.crud(TaskController, middyMiddleware));

export default routes.exec();

The above example will automatically map the following routes to Controller method names, while also auto-creating an instance of TaskController:

  • GET /tasks routes to TaskController.getAll
  • GET /tasks/:id routes to TaskController.get
  • POST /tasks routes to TaskController.create
  • PUT /tasks routes to TaskController.update
  • DELETE /tasks routes to TaskController.delete

Going Further

The package also supports Inversion of Control by injecting an IoC container into your Controllers automatically. Using a RouteBuilder will also add helpers for RBAC for you to write your own middleware to check the user’s RBAC permissions.

Check It Out

If you would like to check it out, use it in a project, or contribute to the open source community, you can check out our Github repo:

--

--