Skip to content

Node JS Template

Published: at 11:14 PM

NodeJS-Template

To develop with this system, you need to know typescript

A Node.Js template

Installation

To install dependencies, run the following command:

npm install

Developing

Important Note!!

By default, the npm start runs the index.js file. To change this, change the line in package.json to "start":"new-command"

Writing a program

Import statement

import { Router, Plugin, RouteHandler, renderTemplate } from "./nodeHttpRouter";

Router declaration

const router = new Router();

App routes

router.addRoute(
  "GET",
  "/greet",
  (req, res) => {
    res.end("Hello, welcome to our server!");
  }, aPlugin, "/new_page"
);

Plugins

const customGreetingPlugin: Plugin = {
  name: "customGreeting",
  handler: async (req, res, params, query) => {
    // Check if a "name" query parameter exists
    if (query && typeof query.name === "string") {
      // Return a custom handler that overrides the default one
      const customHandler: RouteHandler = async (req, res) => {
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.end(`Hello, ${query.name}! This is a custom greeting.`);
      };
      return customHandler;
    }

    // Allow the default handler to proceed if "name" is not provided
    return true;
  },
};
// On a global specific
router.addGlobalPlugin(
    customGreetingPlugin
);
// Route specific
router.addRoute(
    /*Put other parameters here*/
    customGreetingPlugin
);

Testing

// Test cases
const testCases = [
  {
    name: "Match /greet",
    method: "GET",
    path: "/greet",
    expectedMatch: true,
  },
  {
    name: "Match /user/123 with params",
    method: "GET",
    path: "/user/123",
    expectedMatch: true,
    expectedParams: { id: "123" },
  },
  {
    name: "No match for invalid route",
    method: "GET",
    path: "/invalid",
    expectedMatch: false,
  },
];
const results = router.runTests(testCases);
router.printTestResults(results);

Redirection

res.redirect('/path/to/redirect')

Rendering Templates

router.addRoute(
  "GET",
  "/greet",
  (req, res) => {
    res.end(`
    <html>
    <body>
        <h1>Hello, ${name}!</h1>
    </body>
    </html>

    `);
  },
);
router.addRoute(
  "GET",
  "/template",
  async (req, res) => {
    await res.renderTemplate("example.html", { name: "Weston" });
  }
);

Conclusion

🎉 Congrats, you just learned how to use this system

Here’s an example program

import { Router, Plugin, RouteHandler, renderTemplate, EnhancedServerResponse  } from "./nodeHttpRouter";

const router = new Router();

// Global Plugin: Logs each request
const loggerPlugin: Plugin = {
  name: "Logger",
  handler: async (req, res) => {
    console.log(`Request received: ${req.method} ${req.url}`);
    return true; // Allow default handler to proceed
  },
};

// Route Plugin: Checks authentication
const authPlugin: Plugin = {
  name: "Auth",
  handler: async (req, res) => {
    const isAuthenticated = req.headers["x-auth-token"] === "valid-token";
    if (!isAuthenticated) {
      res.writeHead(401, { "Content-Type": "text/plain" });
      res.end("Unauthorized");
      return false; // Halt the request
    }
    return true; // Allow default handler to proceed
  },
};

// Add global plugin
router.addGlobalPlugin(loggerPlugin);

// Route: Static greeting
router.addRoute(
  "GET",
  "/greet",
  (req, res) => {
    res.end("Hello, welcome to our server!");
  },
  [authPlugin] // Auth plugin applied to this route
);

// Route: Render a dynamic template
router.addRoute(
  "GET",
  "/template",
  async (req, res) => {
    await renderTemplate("example.html", { name: "Weston" });
  }
);

// Route: JSON body parsing and response
router.addRoute("POST", "/submit", async (req, res, params, query, body) => {
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify({ received: body }));
});

// Route: Redirect example
router.addRoute("GET", "/redirect", (req, res) => {
    (res as EnhancedServerResponse).redirect("/greet");
});

// Route with parameters
router.addRoute(
  "GET",
  "/user/:id",
  (req, res, params) => {
    res.end(`User ID: ${params?.id}`);
  }
);

// Test cases
const testCases = [
  {
    name: "Match /greet",
    method: "GET",
    path: "/greet",
    expectedMatch: true,
  },
  {
    name: "Match /user/123 with params",
    method: "GET",
    path: "/user/123",
    expectedMatch: true,
    expectedParams: { id: "123" },
  },
  {
    name: "No match for invalid route",
    method: "GET",
    path: "/invalid",
    expectedMatch: false,
  },
];

// Run tests
const results = router.runTests(testCases);
router.printTestResults(results);

// Start the server
const server = router.createServer();
server.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});

But how do run this?

npx tsc
import { ... } from "./nodeHttpRouter"
import { ... } from "./nodeHttpRouter.js"

Next Project
WesMes