Controllers and Routing (HTTP)
Controllers and Routing (HTTP)
In Etherial.TS, we leverage the power of Express, one of the most widely-used and well-maintained libraries in the Node.js ecosystem, to handle HTTP requests and create robust APIs. Express provides a rich set of middleware and routing capabilities, making it an ideal choice for building web applications.
Creating Controllers
To handle routes and organize your application's logic effectively, Etherial.TS introduces the concept of controllers. Controllers are classes that define the behavior of your application's routes. To create a controller, you can use the @Controller() decorator as shown below:
import { Controller } from "etherial/components/http/provider";
@Controller()
export default class UserController {}For best practices, it's recommended to organize your controllers in separate files, with each controller corresponding to a specific feature or resource. For example, a model like User should have its own route controller, typically located in a file like src/routes/users.ts.
Defining Routes
With a controller, you can easily define and manage the routes of your application. Etherial.TS provides decorators that map HTTP verbs to controller methods, simplifying route creation. Here are the available route decorators:
@Get(path: string)
Generate a GET url
@Post(path: string)
Generate a POST url
@Delete(path: string)
Generate a DELETE url
@Put(path: string)
Generate a PUT url
@All(path: string)
Generate a ALL url
For example, to create a GET route for /example, you can use the @Get decorator as follows:
import { Controller, Get, Request, Response } from "etherial/components/http/provider";
@Controller()
export default class UserController {
@Get('/example')
public getExample(req: Request, res: Response) {
res.success({ status: 200, data: {} });
}
}Middleware Integration
Express offers a wide array of middleware options, and Etherial.TS seamlessly integrates with them. You can use middleware to perform various tasks, such as authentication, validation, and error handling. Etherial.TS provides decorators to load external routes and middleware easily:
@Controller()
Will create a new Controller
@ShouldUseRoute(cb: any)
Will load an external route created with Etherial
@ShouldUseMiddleware(cb: any)
Will load an external middleware
This flexibility allows you to plug and play with existing Express middleware or custom middleware tailored to your application's needs.
Route Request and Response
Etherial.TS enhances the Express request and response objects with additional utility methods. You can use these methods to respond to requests with structured JSON data. Here are the available methods:
req.success({ status: number, data: any })
Will respond with a success json, status should be a number from 200 to 299 and data can be anything
req.error({ status: number, errors: []})
Coming...
With these tools at your disposal, you can effortlessly build powerful and maintainable web applications using Etherial.TS and Express.
Best Practices
Designing RESTful APIs with Etherial.TS
When it comes to designing RESTful APIs with Etherial.TS, it's essential to adhere to industry best practices and principles that ensure clarity, maintainability, and consistency. This guide will walk you through the key aspects of creating RESTful APIs using HTTP verbs, URL structure, and naming conventions.
Using HTTP Verbs
RESTful APIs are built around the use of HTTP verbs to perform various actions on resources. Here's a breakdown of how each HTTP verb maps to a specific action:
GET: Use this method to retrieve data from the server. For example,
GET /usersfetches a list of users, andGET /users/{id}retrieves a specific user by their unique identifier.POST: Employ this method to create new resources on the server. For instance,
POST /usersis used to create a new user.PUT: Utilize this method to update existing resources. To update a user's information, use
PUT /users/{id}.DELETE: Employ this method to remove resources from the server. To delete a user, use
DELETE /users/{id}.
By strictly following these HTTP verbs, you ensure that your API endpoints align with their intended actions, promoting clarity and consistency in your API design.
URL Structure
When designing your API's URL structure, it's crucial to keep it clean, intuitive, and reflective of your resources and their relationships. Here are some best practices to consider:
Resource-Centric URLs: Always start your API URLs with the resource (model) name. For example, for a
Userresource, use/users.Use Nouns: The URL should include nouns that represent the resource, not verbs or actions. Avoid URLs like
/createor/update. Instead, use HTTP verbs for actions.Resource Hierarchy: If your API involves resources related to other resources, express this hierarchy through the URL. For example, to get all posts for a specific user, use
/users/{userId}/posts.Use Ids for Specific Resources: When targeting specific resources, use their unique identifiers (usually IDs) in the URL. For instance,
GET /users/123retrieves the user with ID 123.
By structuring your URLs in this manner, you create a more logical and organized API that's easier to understand and navigate.
Examples
Here are some examples of well-designed API endpoints:
Get All Users:
GET /usersGet a Specific User:
GET /users/{id}Create a User:
POST /usersUpdate a User:
PUT /users/{id}Delete a User:
DELETE /users/{id}Get All Posts for a User:
GET /users/{user_id}/posts
By following these principles and using HTTP verbs appropriately, you can create RESTful APIs in Etherial.TS that are both intuitive and adherent to best practices.
When designing your API, remember that simplicity and consistency in your URL structure, along with the proper use of HTTP verbs, are key factors in building a reliable and developer-friendly API.
Last updated
Was this helpful?