Skip to main content
Orionjs provides a clean and type-safe way to define HTTP routes through the @Routes() and @Route() decorators. This approach allows you to organize your API endpoints in controller classes with dependency injection support.

Creating a Routes Controller

A routes controller is a class decorated with @Routes() that contains methods decorated with @Route() to define individual endpoints:

Route Definition Options

The createRoute() function accepts the following options:

Available Options

Route Handlers

Route handlers (the resolve function) receive the request object and any middleware-injected properties:

Handler Parameters

Route handlers typically receive:
  • req: Express Request object with params, query, and body
  • Any context injected by middleware (like viewer, authenticated user)

Return Values

Route handlers should return an object with:
You can also access the Express response object through the request:

Route Parameters

You can access route parameters through the request object, and they will be type-safe if you specify the path with parameter placeholders:

Query Parameters

You can define and validate query parameters using the queryParams option:

Request Body

You can define and validate request body parameters using the bodyParams option:

Error Handling

Orionjs automatically handles errors thrown in route handlers:

Example: File Uploads

For handling file uploads, you could use the multer middleware:

CORS and Security

There are two ways to apply middleware in Orionjs:

1. Route-Specific Middleware

Apply middleware to specific routes using the middlewares option:

2. Global Middleware

Apply middleware to all routes using the HTTP app:

Custom Response Types

You can define custom response formats for non-JSON responses:

Authentication and Authorization

You can implement authentication and authorization using middleware:

Starting the HTTP Server

To start the HTTP server:

Best Practices

  1. Organize by Domain: Group related routes in the same controller class.
  2. Use Parameter Validation: Define schema for query, body, and response parameters.
  3. Keep Route Handlers Simple: Focus on request handling logic, move business logic to services.
  4. Leverage Dependency Injection: Use @Inject(() => Service) for clean service integration.
  5. Implement Proper Error Handling: Catch and handle expected errors appropriately.
  6. Apply Security Middleware: Use middleware for authentication, CSRF protection, etc.
  7. Clear Status Codes: Use appropriate HTTP status codes for different responses.
  8. Document Your API: Add clear descriptions for each endpoint and its parameters.
  9. Follow RESTful Principles: Use appropriate HTTP methods for different operations.
  10. Implement Rate Limiting: Protect against abuse with rate limiting middleware.