Latest Version: 1.0.6

The ability to create routes using the regular Express routers and test them directly using Express is powerful, but it comes with problems. Express is about an MB of code for your 2 KBs worth of routering.

Our custom router helps you achieve the same results while using the same syntax and testing. You can test your code without launching a server or installing Express.

Router

It is a quick replacement of the Express router which supports the same subset of methods.

Example

var { Router } = require("cl_routes");

var router = new Router();

// You can use middlewares
router.use(basicAuth);

// and routes
router.get("/employee", getAllEmployees);
router.get("/employee/:id", getEmployee);
router.post("/employee", createEmployee);
router.delete("/employee/:id", deleteEmployee);
router.patch("/employee/:id", updateEmployee);

Using Custom Router

The custom router is required for several new features, to indicate you are using the new router, add the following to your exports:

module.exports = { router, config: {
    type: "cl-router" // Set type to "cl-router"
}};

Nested Routers

It is possible to use nested routers, however, they will be flattened into a single router. Middleware and paths will be preserved.

var router = new Router();
var router2 = new Router();

router.get("/");
router.post("/");

router2.get("/");
router2.post("/");
// Works as long as path is unique
router.use("/path", router2);

Methods (For Developers)

expressRouter(): Express.Router:

Converts your Router to an Express Router with the same routes and middleware.

call(method, path, …params): void:

Calls a handler for a given method and path passing the parameters in the handler.

Migrating from Express to custom Routes

Migrating your routes from Express to custom routes is quite easy, just follow the following steps:

  1. Install cl_routes if is not already installed:
    • yarn add cl_routes@latest --registry http://localhost:4873
  2. Replace Express router with cl_routes
    • Import the following instead of Express
      var { Router } = require("cl_routes");
      var router = new Router(); // Add the "new" keyword.
  3. Add the following to your config
    • type: "cl-router"

Migrating Tests

Currently, there is no way to migrate your tests. Instead, you will convert it to an Express Router. In your development server, replace
app.use(router);
with
app.use(router.expressRouter());

Update Log

1.0.6 (7/15/2023)

  • Added support for dynamic routes
  • Added support for converting to Express Router
Tagged:

Leave a Reply

Your email address will not be published. Required fields are marked *