Skip to content

Block

The defineBlock function in GamanJS is a powerful abstraction for organizing services, routes, middlewares, and dependencies into a cohesive unit. Blocks are reusable, isolated modules that can be composed together to form a full-featured application structure.

Blocks serve as the foundation for modular architecture in GamanJS. Each block can encapsulate:

  • Services
  • Routes
  • Middlewares
  • Integrations
  • Nested blocks (submodules)
  • Custom error handlers
  • Custom 404 handlers

A block is defined using the defineBlock() function and typically exported from a file such as *.block.ts.

  • path?: The base path prefix for all routes in this block.
  • includes?: An array of elements (middleware, child blocks, or integrations) to be applied and composed within the current block. Useful for grouping reusable logic, nested modules, or third-party extensions into a single composable unit.
  • bindings?: Injected values such as services or external dependencies (e.g., database client, logger).
  • routes?: Route factories associated with this block.
  • priority?: Determines the execution order of blocks.
  • error?: Custom error handler for exceptions thrown inside the block.
  • 404?: Handler for undefined routes in this block.
example.block.ts
export default defineBlock({
path: "/user",
bindings: {
userService,
},
routes: [userRoutes],
});

After that, you can add your block to main.block.ts

main.block.ts
export default defineBlock({
path: "/",
includes: [userBlock],
});
  • Group related logic (routes + services) into their own block.
  • Use includes for reusable middlewares.
  • Use priority to control registration order for overlapping paths.
  • Compose blocks using the blocks array for scalable structure.
  • Encourages separation of concerns.
  • Promotes reusability and testability.
  • Enables clear hierarchical module structure.

Blocks in GamanJS are a flexible and powerful way to build modular backend applications. They unify routing, services, and context-based dependencies in a clean, declarative format that supports scaling and maintainability.