LiteNode's logo

LiteNode

Docs GitHub logo
▶ Usage

Documentation

Combining Routers

You can merge routers or nest routers under a specific path:

merge

Signature:

merge(routerToMerge: LiteNode, ...middlewares: RouteHandler[]): void

Merges routes from another LiteNode instance into the current LiteNode instance.

Example:

// Create a LiteNode instance for user routes
const userRouter = new LiteNode()

// Define a route for user profile
userRouter.get("/profile", (req, res) => {
    // Set response headers
    res.writeHead(200, { "Content-Type": "text/plain" })
    // Send response with user profile data
    res.end("User Profile")
})

// Create a LiteNode instance for API routes
const apiRouter = new LiteNode()

// Define a route for API data
apiRouter.get("/data", (req, res) => {
    // Set response headers
    res.writeHead(200, { "Content-Type": "application/json" })
    // Send response with JSON data
    res.end(JSON.stringify({ message: "API Data" }))
})

// Merge userRouter and apiRouter into the main LiteNode app
app.merge(userRouter)
app.merge(apiRouter)

// Merge example with middleware function
app.merge(apiRouter, myMiddlewareFunction)

Accessing http://localhost:5000/profile will respond with "User Profile".

Accessing http://localhost:5000/data will respond with the JSON object {"message": "API Data"} in JSON format.


nest

Signature:

nest(prefix: string, routerToNest: LiteNode, ...middlewares: RouteHandler[]): LiteNode

Nests routes from another LiteNode instance under a specific prefix.

Example:

// Create a LiteNode instance for admin routes
const adminRouter = new LiteNode()

// Define a route for admin dashboard
adminRouter.get("/dashboard", (req, res) => {
    // Set response headers
    res.writeHead(200, { "Content-Type": "text/plain" })
    // Send response with admin dashboard data
    res.end("Admin Dashboard")
})

// Nest the adminRouter under the "/admin" prefix in the main LiteNode app
app.nest("/admin", adminRouter)

// Nest example with middleware function
app.nest("/admin", adminRouter, myMiddlewareFunction)

Accessing http://localhost:5000/admin/dashboard will respond with "Admin Dashboard".


Merging and Nesting with Middlewares

The examples above demonstrate how to merge and nest while applying middleware.
However, an application in production will likely consist of multiple routes.
Utilizing the merge and nest methods with one or many middlewares will impact the parent routes and consequently the child routes by applying the defined middleware(s) to them.
To mitigate this behavior, initialize the merged LiteNode instance without specifying a directory for serving static files:

const app = new LiteNode()

// Create a LiteNode instance that skips serving static assets
const subApp = new LiteNode("__NO_STATIC_DIR__")

// Global middleware
app.use(async (req, res) => {
    console.log(req.url)
})

// Route based middleware
async function myMiddleware(req, res) {
    console.log("A middleware function that will be applied to a particular route.")
}

// Define the application's entry route
app.get("/", (req, res) => {
    res.end("Hello, LiteNode!")
})

// Define a route for the sub application
subApp.get("/sub", (req, res) => {
    res.end("Sub application of the main LiteNode app")
})

// Merge subApp into the main LiteNode app
// Apply myMiddleware to the "/sub" route only!
app.merge(subApp, myMiddleware)

// Nest subApp under the "/app" prefix in the main LiteNode app
// Apply myMiddleware to the "/app/sub" route only!
app.nest("/app", subApp, myMiddleware)

Keep in mind the following from the above example:

  1. While subApp is set to prevent serving static files, it can still load the files from the "static" directory of app since it's merged into it.
  2. Assuming a defined /app route in the app instance, this route will not be affected by myMiddleware. This is because middleware applied to nested routes only impacts those routes and their children.
  3. Nested instance(s) of LiteNode are set to skip serving static assets by default.
Information SVG Nested routes are by default defined as a LiteNode instance that skips serving static assets to prevent unintended traversal of their middleware(s) in the reverse direction.

Merge and Nest Summary

  1. Merge Feature:

    • The merge method allows merging routes from another router into the current LiteNode instance. This feature is beneficial for modularizing routes and separating concerns.
    • It enables developers to combine routes from multiple routers, along with their respective middleware stacks, into a single router instance.
    • Merging routes can help in organizing code logically, promoting code reuse, and maintaining a clean project structure.
    • The merge feature enhances the framework's extensibility, allowing developers to compose complex routing structures efficiently.
  2. Nest Feature:

    • The nest method facilitates nesting routers within one another, creating a hierarchical structure for route handling.
    • Nested routers enable developers to modularize and encapsulate route handling for specific parts of an application.
    • This feature enhances code readability and maintainability by grouping related routes together.
    • Nested routers can have their own middleware stack, allowing for middleware specific to certain route hierarchies.
    • By nesting routers, developers can build applications with complex routing requirements while keeping the codebase organized and manageable.

In summary, both the merge and nest features contribute to the flexibility and maintainability of the framework. They empower developers to structure their applications in a modular and hierarchical manner, facilitating code reuse and promoting a cleaner architectural design.

Content