Routing - 7TogkID/gaman GitHub Wiki

GamanJS Routing Documentation

Overview

The GamanJS routing system is designed to be flexible and intuitive, using a tree-like structure to represent routes. This Tree Routing approach enables developers to create modular and maintainable routing configurations that resemble the branches of a tree.


Defining Routes

Routes in GamanJS are specified within the routes property of a Block. They support various HTTP methods and path-specific middleware.

Example: Tree Routing

Here is an example of defining routes directly within a Block using the tree structure:

import { defineBlock } from "gaman";

export default defineBlock({
  routes: {
    "/getUser/*": (ctx) => {
      // Middleware for all routes under /getUser/*
    },
    "/getUser": {
      ALL: (ctx) => {
        return Response.json({ message: "OK!" });
      },
      "/detail": {
        GET: (ctx) => {
          return Response.json({ message: "Detail Get User" });
        },
        "/super-detail": {
          GET: (ctx) => {
            return Response.json({ message: "Super-Detail Get User" });
          },
        },
      },
    },
  },
});

Supported Methods

  • ALL: Middleware or handler that matches all HTTP methods.
  • HTTP Methods: Use GET, POST, PUT, DELETE, etc., for specific HTTP requests.

Modularizing Routes with defineTree

When the route tree becomes too large or complex, you can use the defineTree function to split the configuration into separate files. This approach improves readability and maintainability.

Step 1: Create a Tree

Define a tree in a separate file (e.g., userDetail.tree.ts).

import { defineTree } from "gaman";

export default defineTree({
  ALL: (ctx) => {
    return Response.json({ message: "OK!" });
  },
  "/detail": {
    GET: (ctx) => {
      return Response.json({ message: "Detail Get User" });
    },
    "/super-detail": {
      GET: (ctx) => {
        return Response.json({ message: "Super-Detail Get User" });
      },
    },
  },
});

Step 2: Integrate the Tree into a Block

Import the tree into the Block file and integrate it into the routes property.

import { defineBlock } from "gaman";
import userDetailTree from "./userDetail.tree";

export default defineBlock({
  routes: {
    "/getUser/*": (ctx) => {
      // Middleware for all routes under /getUser/*
    },
    "/getUser": userDetailTree, // Integrate the tree
  },
});

Best Practices

  • Use defineTree for Complex Routes: Split large route configurations into smaller, focused files.
  • Leverage Middleware: Use ALL handlers for shared logic across all subroutes.
  • Organize by Feature: Group related routes into Blocks and Trees for clarity.

Additional Notes

  • Routes defined in defineTree files behave exactly like those defined directly in a Block.
  • Ensure that Tree files are imported correctly to avoid runtime errors.

For more details, refer to the official GamanJS documentation or examples.