aboutsummaryrefslogtreecommitdiff
path: root/source/library/router/index.md
blob: 65e01cebb27d954e8ffb8f66642eaee79d860524 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# Router Class Documentation

The `Router` class is designed to handle routing of HTTP requests based on the request path. It allows you to define routes with dynamic parameters and associate them with handler functions.

## Constructor

### `new Router(request, environment, context)`

Creates a new instance of the `Router` class.

- **Parameters:**

  - `request` (Request): The incoming request object.
  - `environment` (Environment): The environment object.
  - `context` (Context): The context object.

- **Returns:** A new `Router` instance.

---

## Methods

### `add(path, handler)`

Adds a new route to the router.

- **Parameters:**

  - `path` (string): The path to match. Dynamic segments can be defined using `:paramName`.
  - `handler` (function): The handler function to call if the path matches. The handler receives `request`, `environment`, and `context` as arguments.

- **Returns:** The `Router` instance for chaining.

- **Example:**
  ```javascript
  router.add("/users/:id", (request, environment, context) => {
    const userId = router.parameters.id;
    return new Response(`User ID: ${userId}`);
  });
  ```

---

### `respond(body, status = 200)`

Helper function to create a JSON response.

- **Parameters:**

  - `body` (object): The JSON object to respond with.
  - `status` (number, optional): The HTTP status code. Defaults to `200`.

- **Returns:** A `Response` object.

- **Example:**
  ```javascript
  return router.respond({ message: "Success" }, 200);
  ```

---

### `route()`

Routes the incoming request to the appropriate handler based on the request path.

- **Returns:** A `Response` object.

- **Behavior:**

  - Matches the request path against the registered routes.
  - Extracts dynamic parameters from the path and stores them in `router.parameters`.
  - Calls the corresponding handler function.
  - Returns a `404` response if no route matches.
  - Returns a `500` response in case of unexpected errors.

- **Example:**
  ```javascript
  const response = router.route();
  ```

---

## Example Usage

```javascript
import Router from "./router.js";

const router = new Router(request, environment, context);

router
  .add("/hello", () => {
    return new Response("Hello, world!");
  })
  .add("/users/:id", (request, environment, context) => {
    const userId = router.parameters.id;
    return new Response(`User ID: ${userId}`);
  });

const response = router.route();
```

---

## Error Handling

- **404 Not Found:** If no route matches the request path, the `Router` responds with:

  ```json
  {
    "error": "Route not found: /path"
  }
  ```

- **500 Internal Server Error:** If an unexpected error occurs, the `Router` responds with:
  ```json
  {
    "error": "Internal Server Error: error message"
  }
  ```

---

## Notes

- Paths are normalized by removing trailing slashes.
- Dynamic parameters in paths (e.g., `:id`) are extracted and stored in the `parameters` property of the `Router` instance.
- The `add` method uses regular expressions to match paths efficiently.