# Routes

Routing is a mechanism for handling HTTP requests based on the method (GET, POST, PUT, DELETE, etc.) and URL path. In fhyts, routing is easily managed through the rq method on the router instance provided by the framework.

## Creating Routes (routes.ts)

#### Import and Initialization

First, import FhyEngine and create a shortcut to register routes with specific HTTP methods.

```javascript
import { FhyEngine } from 'fhyts';

// Create a shortcut function to register routes
const Use = ((r) => r.rq.bind(r))(FhyEngine.getInstance().r);
```

#### Route Function

Create a Route function that contains all your route definitions.

```javascript
export function Route() {
  Use('GET', '/', (req, res) => {
    res.send('Welcome to the main page!');
  });

  Use('GET', '/users/:id', (req, res) => {
    const { id } = req.params;
    res.send(`User details with ID: ${id}`);
  });
}
```

#### CRUD Routing Example

Here's an example of implementing CRUD routing for resource users:

```javascript
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
];

export function Route() {
  // CREATE: Add a new user
  Use('POST', '/users', (req, res) => {
    const newUser = req.body;
    newUser.id = users.length + 1;
    users.push(newUser);
    res.json(newUser);
  });

  // READ ALL: Get a list of all users
  Use('GET', '/users', (req, res) => {
    res.json(users);
  });

  // READ ONE: Get user by ID
  Use('GET', '/users/:id', (req, res) => {
    const user = users.find(u => u.id === Number(req.params.id));
    if (!user) {
      return res.status(404).send('User not found');
    }
    res.json(user);
  });

  // UPDATE: Updates user data based on ID
  Use('PUT', '/users/:id', (req, res) => {
    const idx = users.findIndex(u => u.id === Number(req.params.id));
    if (idx === -1) {
      return res.status(404).send('User not found');
    }
    users[idx] = { ...users[idx], ...req.body };
    res.json(users[idx]);
  });

  // DELETE: Deletes user by ID
  Use('DELETE', '/users/:id', (req, res) => {
    const idx = users.findIndex(u => u.id === Number(req.params.id));
    if (idx === -1) {
      return res.status(404).send('User not found');
    }
    const deletedUser = users.splice(idx, 1);
    res.json(deletedUser[0]);
  });
}
```

## Use Function Parameters

| Parameter | Type | Description                                                                               |
| --------- | ---------- | --------------------------------------------------------------------------------------- |
| `method`  | `string`   | HTTP Methods ('GET', 'POST', 'PUT', 'DELETE', etc.)                              |
| `path`    | `string`   | The URL path to be handled, can use dynamic parameters (e.g. `/users/:id`) |
| `handler` | `function` | Functions that handle requests and responses (` (req, res) => { ... }`)                   |

## Request and Response Objects

* **req.params**: Contains URL parameters defined in the route (e.g., :id in /users/:id).
* **req.body**: Contains the request body data (typically used in POST and PUT).
* **res.send(data)**: Sends text data as a response to the client.
* **res.json(data)**: Sends JSON data as a response to the client.
* **res.status(code)**: Sets the HTTP status of the response.

## Enable

Call the **Route()** function before starting the server to register all routes:

```javascript
import { Route } from './routes';

async function Server() {
  // ...
	
  Route(); // Register all routes
  
  // ...server initialization
}
```

## Next

You can proceed to [Controllers](#controllers) to separate business logic from routing.