galbe 0.12.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/bin/commands/generate/code/openapi.parser.ts +18 -11
  2. package/bin/commands/generate/index.ts +3 -1
  3. package/bin/commands/generate/model.ts +153 -0
  4. package/bin/commands/generate/spec.ts +7 -5
  5. package/bin/util.ts +9 -0
  6. package/package.json +8 -4
  7. package/src/types.ts +1 -1
  8. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -35
  9. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -23
  10. package/.github/workflows/build_test.yml +0 -17
  11. package/.github/workflows/deploy_website.yml +0 -20
  12. package/.github/workflows/release.yml +0 -39
  13. package/.prettierrc +0 -10
  14. package/bun.lock +0 -904
  15. package/bunfig.toml +0 -2
  16. package/docs/CONTRIBUTING.md +0 -105
  17. package/docs/cli.md +0 -343
  18. package/docs/configuration.md +0 -80
  19. package/docs/context.md +0 -104
  20. package/docs/error-handler.md +0 -54
  21. package/docs/getting-started.md +0 -164
  22. package/docs/handler.md +0 -119
  23. package/docs/hooks.md +0 -90
  24. package/docs/plugins.md +0 -146
  25. package/docs/router.md +0 -10
  26. package/docs/routes.md +0 -133
  27. package/docs/schemas.md +0 -327
  28. package/test/hooks.test.ts +0 -200
  29. package/test/parser.test.ts +0 -1358
  30. package/test/plugins.test.ts +0 -239
  31. package/test/requests.test.ts +0 -917
  32. package/test/resources/image.png +0 -0
  33. package/test/resources/object.badSyntax.json +0 -8
  34. package/test/resources/object.json +0 -8
  35. package/test/resources/object.missing.json +0 -6
  36. package/test/resources/static/chameleon.png +0 -0
  37. package/test/resources/static/index.html +0 -13
  38. package/test/resources/static/sub/index.html +0 -13
  39. package/test/resources/static/sub/other.html +0 -13
  40. package/test/resources/test.route.comment.ts +0 -58
  41. package/test/resources/test.route.empty.ts +0 -9
  42. package/test/responses.test.ts +0 -483
  43. package/test/routeFiles.test.ts +0 -239
  44. package/test/router.test.ts +0 -231
  45. package/test/test.utils.ts +0 -109
  46. package/test/types.test.ts +0 -909
  47. package/tsconfig.json +0 -23
package/bunfig.toml DELETED
@@ -1,2 +0,0 @@
1
- [install]
2
- registry = "https://registry.npmjs.org/"
@@ -1,105 +0,0 @@
1
- # Contributing to Galbe
2
-
3
- First off, thank you for considering contributing to our project! We appreciate your time and effort and want to make this as easy and transparent as possible for everyone.
4
-
5
- ## Create an Issue
6
-
7
- If you encounter a bug, want to propose a new feature, or something that could be improved, please create an issue. Here's how:
8
-
9
- 1. **Check Existing Issues**: Before creating a new issue, please search the [existing issues](https://github.com/pierre-cm/galbe/issues) to see if someone else has already reported the same problem or suggested the same feature.
10
-
11
- 2. **Open a New Issue**: If your issue is new, [open a new issue](https://github.com/pierre-cm/galbe/issues/new/choose) and provide the following details:
12
-
13
- - **Title**: A concise summary of the issue.
14
- - **Description**: A detailed description of the problem or suggestion. Include steps to reproduce the issue if applicable.
15
- - **Screenshots**: If possible, include screenshots or other visual aids that help explain the issue.
16
- - **Environment**: Mention the environment in which you encountered the issue (e.g., OS, Bun version).
17
- - **Labels**: Assign appropriate labels (e.g., bug, enhancement) to help categorize your issue.
18
-
19
- 3. **Follow Up**: Once your issue is submitted, be ready to provide additional information if requested. We'll do our best to address the issue promptly.
20
-
21
- ## Create a Pull Request
22
-
23
- ### 1. Fork the Repository
24
-
25
- If you haven't already, [fork Galbe's repository on GitHub](https://github.com/pierre-cm/galbe/fork). This will create a copy of this repository under your GitHub account.
26
-
27
- ### 2. Clone Your Fork
28
-
29
- Clone the forked repository to your local machine:
30
-
31
- ```bash
32
- git clone https://github.com/<your-username>/galbe.git
33
- cd galbe
34
- ```
35
-
36
- ### 3. Create a New Branch
37
-
38
- Before making any changes, create a new branch for your work. Branches help keep your changes separate from the main branch and make it easier to review and merge:
39
-
40
- ```bash
41
- git checkout -b feature/your-feature-name
42
- ```
43
-
44
- Use a descriptive name for your branch to indicate what you are working on.
45
-
46
- ### 4. Make Your Changes
47
-
48
- Make the necessary changes in your branch. Be sure to follow the project's coding style and best practices.
49
-
50
- ### 5. Commit Your Changes
51
-
52
- Once you’ve made your changes, commit them with a clear and descriptive message:
53
-
54
- ```bash
55
- git add .
56
- git commit -m "Add feature X to do Y"
57
- ```
58
-
59
- ### 6. Push to Your Fork
60
-
61
- Push your changes to your forked repository on GitHub:
62
-
63
- ```bash
64
- git push origin feature/your-feature-name
65
- ```
66
-
67
- ### 7. Create a Pull Request
68
-
69
- Once your changes are pushed to GitHub, you can create a pull request. Go to the [original repository](https://github.com/pierre-cm/galbe) on GitHub, and you should see an option to create a pull request from your branch.
70
-
71
- - Make sure to provide a detailed description of your changes and why they are necessary.
72
- - Link any related issues if applicable.
73
- - If your pull request is still a work in progress, mark it as a draft to let others know that you are not yet ready for a review.
74
-
75
- ### 8. Respond to Feedback
76
-
77
- Once your pull request is submitted, it will be reviewed by the project maintainers. They may ask for changes or provide feedback. Please be responsive and make the necessary adjustments.
78
-
79
- ### Coding Standards
80
-
81
- Please follow these coding standards to ensure consistency across the project:
82
-
83
- - **Code Style**: Follow the [style guide]().
84
- - **Commit Messages**: Use clear and descriptive commit messages.
85
- - **Documentation**: Update documentation where applicable. This includes comments in the code and other documentation files under the `docs` directory.
86
-
87
- ## Code of Conduct
88
-
89
- We are committed to creating a welcoming and inclusive environment for everyone. To ensure this, all contributors are expected to adhere to the following guidelines:
90
-
91
- 1. **Be Respectful**: Treat everyone with respect. Disagreements are inevitable, but it's important to remain courteous and constructive. Personal attacks, harassment, or offensive comments will not be tolerated.
92
-
93
- 2. **Collaborate Openly**: Collaboration is key to the success of the project. Be open to feedback and suggestions from others. Constructive criticism should be welcomed and given in a positive manner.
94
-
95
- 3. **Resolve Disagreements Constructively**: If you find yourself in a disagreement, seek to resolve it in a way that is constructive and respectful. If necessary, involve a project maintainer to help mediate.
96
-
97
- 4. **Report Issues**: If you witness or experience any behavior that violates this Code of Conduct, please report it immediately to the project maintainers. We take all reports seriously and will address them promptly.
98
-
99
- By participating in this project, you agree to abide by this Code of Conduct.
100
-
101
- ## Getting Help
102
-
103
- If you have any questions or need help, feel free to open an issue or contact one of the maintainers.
104
-
105
- Thank you for your contribution!
package/docs/cli.md DELETED
@@ -1,343 +0,0 @@
1
- # CLI
2
-
3
- A Command Line Interface is shipped with Galbe package. You can use it to perform useful tasks around your application.
4
-
5
- After [Installing Galbe](getting-started.md#automatic-installation), the CLI will be available locally to your project.
6
-
7
- However, if you want to use it directly from your terminal, you must either:
8
-
9
- Install it globally using the following command:
10
-
11
- ```bash
12
- $ bun i -g galbe
13
- ```
14
-
15
- Or run it with `bunx`:
16
-
17
- ```bash
18
- $ bunx galbe
19
- ```
20
-
21
- ## dev
22
-
23
- Start a dev server running your Galbe application.
24
-
25
- #### Arguments
26
-
27
- | Name | Description |
28
- | ----- | -------------------------------------------------------- |
29
- | index | The js or ts file that export your Galbe server instance. |
30
-
31
- #### Options
32
-
33
- | Short | Long | Descritpion | Default |
34
- | ----- | --------------- | --------------------------- | ------- |
35
- | -p | --port | port number [1-65535] | 3000 |
36
- | -w | --watch | watch file changes dir | false |
37
- | -wi | --watchignore | ignored watch files regex | |
38
- | -nc | --noclear | don't clear on file changes | false |
39
-
40
- #### Example
41
-
42
- index.js
43
-
44
- ```js
45
- import { Galbe } from 'galbe'
46
-
47
- const g = new Galbe()
48
- g.get('example', () => '')
49
-
50
- export default g
51
- ```
52
-
53
- ```bash
54
- $ galbe dev index.js -p 7357 -w
55
- 🏗️ Constructing routes
56
-
57
- [GET] /example
58
-
59
- done
60
-
61
- 🚀 Server running at http://localhost:7357
62
- ```
63
-
64
- ## build
65
-
66
- Bundle your Galbe application.
67
-
68
- #### Arguments
69
-
70
- | Name | Description |
71
- | ----- | -------------------------------------------------------- |
72
- | index | The js or ts file that export your Galbe server instance. |
73
-
74
- #### Options
75
-
76
- | Short | Long | Description | Default |
77
- | ----- | --------- | ------------------------------ | -------- |
78
- | -o | --out | output directory | dist/app |
79
- | -C | --compile | create a standalone executable | false |
80
- | -c | --config | bun config (js or ts) | |
81
-
82
- #### Example
83
-
84
- index.js
85
- ```js
86
- import { Galbe } from 'galbe'
87
-
88
- export default new Galbe()
89
- ```
90
-
91
- ```bash
92
- $ galbe build index.js
93
- ```
94
-
95
- ## generate
96
-
97
- Generate resources around your Galbe application.
98
-
99
- ### client
100
-
101
- Generate a client for your Galbe application.
102
-
103
- #### Arguments
104
-
105
- | Name | Description |
106
- | ----- | -------------------------------------------------------- |
107
- | index | The js or ts file that export your Galbe server instance. |
108
-
109
- #### Options
110
-
111
- | Short | Long | Description | Default |
112
- | ----- | -------- | -------------------------- | ------------------------------------ |
113
- | -o | --out | output file | dist/(client.ts \| client.js \| cli) |
114
- | -t | --target | build target [ts, js, cli] | ts |
115
-
116
- #### Examples
117
-
118
- Let's first setup a new Galbe project:
119
-
120
- ```bash
121
- $ bun create galbe galbe-example --template hello --lang ts
122
- $ cd galbe-example
123
- $ bun install
124
- ```
125
-
126
- ##### JS or TS client
127
-
128
- To generate a JS or TS client of that application, you can run the following command:
129
-
130
- ```bash
131
- $ galbe generate client index.ts
132
- ```
133
-
134
- This will generate a `dist/client.ts` client lib by default.
135
- You can import it and use it like in the following example:
136
-
137
- client_example.ts
138
-
139
- ```ts
140
- import HelloClient from './dist/client'
141
-
142
- const client = new HelloClient({ server: { url: 'http://localhost:3000' } })
143
-
144
- const response = await client.hello('Bob', { query: { age: 42 } })
145
- // This is equivalent as calling
146
- // const response = await client.get["/hello/:name"]("Bob", { query: { age: 42 } })
147
-
148
- if (response.ok) console.log(await response.body())
149
- // Hello Bob! You're 42 y.o.
150
- ```
151
-
152
- ##### CLI client
153
-
154
- To generate a CLI of that application, you can run the following command:
155
-
156
- ```bash
157
- $ galbe generate client index.ts -t cli
158
- ```
159
-
160
- This will generate a `cli` binary file under `dist` directory by default.
161
-
162
- ```bash
163
- $ ./dist/cli --help
164
- Usage: galbe-example [options] [command]
165
-
166
- Options:
167
- -V, --version output the version number
168
- -h, --help display help for command
169
-
170
- Commands:
171
- hello [options] Greeting endpoint
172
- help [command] display help for command
173
- ```
174
-
175
- ```bash
176
- $ ./dist/cli hello --help
177
- Usage: galbe-example hello [options] <name>
178
-
179
- Greeting endpoint
180
-
181
- Arguments:
182
- name name argument
183
-
184
- Options:
185
- -%f, --%format [string] response format ['s','h','b','t','p'] (default: ["s","b","p"])
186
- -%h, --%header <string...> request header formated as headerName=headerValue (default: [])
187
- -%q, --%query <string...> query param formated as paramName=paramValue (default: [])
188
- -%b, --%body <string> request body (default: "")
189
- -%bf, --%bodyFile <path> request body file (default: "")
190
- -a, --age <number>
191
- -h, --help display help for command
192
- ```
193
-
194
- ```bash
195
- $ ./dist/cli hello Pierre -a 29
196
- 200
197
- Hello Pierre! You're 29 y.o.
198
- ```
199
-
200
- > [!IMPORTANT]
201
- > A `GCLI_SERVER_URL` environment variable must be defined. It should indicate the url of the Galbe server you want to target.
202
- > In that specific case `http://localhost:3000`.
203
-
204
- ### spec
205
-
206
- Generate the spec of your Galbe application.
207
-
208
- #### Arguments
209
-
210
- | Name | Description |
211
- | ----- | -------------------------------------------------------- |
212
- | index | The js or ts file that export your Galbe server instance. |
213
-
214
- #### Options
215
-
216
- | Short | Long | Description | Default |
217
- | ----- | -------- | ------------------------------------------------ | ----------------------- |
218
- | -t | --target | spec target [openapi:3.0:json, openapi:3.0:yaml] | openapi:3.0:yaml |
219
- | -b | --base | base spec file | |
220
- | -o | --out | output file | spec/api.(yaml \| json) |
221
-
222
- #### Example
223
-
224
- Let's try to generate the spec of the project defined in the previous client section. You can then run:
225
-
226
- ```bash
227
- $ galbe generate spec index.ts
228
- ```
229
-
230
- This should generate the following `spec/api.yaml` file:
231
-
232
- ```yaml
233
- openapi: 3.0.3
234
- info:
235
- title: galbe-app
236
- version: 0.1.0
237
- paths:
238
- /hello/{name}:
239
- get:
240
- summary: Greeting endpoint
241
- operationId: hello
242
- parameters:
243
- - name: age
244
- in: query
245
- required: true
246
- schema:
247
- type: integer
248
- responses:
249
- '200':
250
- description: OK
251
- content:
252
- text/plain:
253
- schema:
254
- type: string
255
- ```
256
-
257
- ### code
258
-
259
- Generate the code and project structure from spec.
260
-
261
- #### Arguments
262
-
263
- | Name | Description |
264
- | ----- | ---------------------------------------------------------- |
265
- | input | The input spec file from which the code will be generated. |
266
-
267
- #### Options
268
-
269
- | Short | Long | Description | Default |
270
- | ----- | -------- | ------------------------------------------------- | -------------------------- |
271
- | -f | --format | input format [openapi:3.0:yaml, openapi:3.0:json] | openapi:3.0:(yaml \| json) |
272
- | -t | --target | source target [ts, js] | ts |
273
- | -o | --out | output dir | src |
274
- | -F | --force | force overriding output | false |
275
-
276
- #### Example
277
-
278
- For that example, we will generate the Galbe source code from the [Swagger Petstore Openapi spec](https://petstore3.swagger.io/).
279
-
280
- First, initiate a new bun project and install the galbe dependency.
281
-
282
- ```bash
283
- $ mkdir petstore && cd petstore
284
- $ bun init && bun add galbe
285
- ```
286
-
287
- Now modify the `index.ts` file with the following content:
288
-
289
- ```ts
290
- import { Galbe } from 'galbe'
291
-
292
- export default new Galbe()
293
- ```
294
-
295
- Then download the petstore json spec from Swagger website into `petstore.spec.json`:
296
-
297
- ```bash
298
- $ curl -o petstore.spec.json https://petstore3.swagger.io/api/v3/openapi.json
299
- ```
300
-
301
- You can now generate the sources from the petstore spec:
302
-
303
- ```bash
304
- $ galbe generate code petstore.spec.json
305
- ```
306
-
307
- This should generate the code of our application in the `src` directory by default.
308
-
309
- To test that the code was successfully generated, you can run:
310
-
311
- ```bash
312
- $ galbe dev index.ts
313
- 🏗️ Constructing routes
314
-
315
- src/routes/pet.route.ts
316
- [PUT] /pet Update an existing pet
317
- [POST] /pet Add a new pet to the store
318
- [GET] /pet/findByStatus Finds Pets by status
319
- [GET] /pet/findByTags Finds Pets by tags
320
- [GET] /pet/:petId Find pet by ID
321
- [POST] /pet/:petId Updates a pet in the store with form data
322
- [DELETE] /pet/:petId Deletes a pet
323
- [POST] /pet/:petId/uploadImage uploads an image
324
-
325
- src/routes/store.route.ts
326
- [GET] /store/inventory Returns pet inventories by status
327
- [POST] /store/order Place an order for a pet
328
- [GET] /store/order/:orderId Find purchase order by ID
329
- [DELETE] /store/order/:orderId Delete purchase order by ID
330
-
331
- src/routes/user.route.ts
332
- [POST] /user Create user
333
- [POST] /user/createWithList Creates list of users with given input array
334
- [GET] /user/login Logs user into the system
335
- [GET] /user/logout Logs out current logged in user session
336
- [GET] /user/:username Get user by user name
337
- [PUT] /user/:username Update user
338
- [DELETE] /user/:username Delete user
339
-
340
- done
341
-
342
- 🚀 Server running at http://localhost:3000
343
- ```
@@ -1,80 +0,0 @@
1
- # Configuration
2
-
3
- ## Configuring Galbe
4
-
5
- By default, Galbe automatically attempts to resolve a configuration file named `galbe.config.{js,ts}` located in the same directory as your entry file.
6
-
7
- The configuration file should export a default object containing your settings:
8
-
9
- ```js
10
- export default {
11
- // config properties
12
- }
13
- ```
14
-
15
- Alternatively, you can pass your configuration directly to your Galbe server during instantiation, as shown below:
16
-
17
- ```ts
18
- import { Galbe } from "galbe"
19
-
20
- const galbe = new Galbe({
21
- // config properties
22
- })
23
-
24
- export default galbe
25
- ```
26
-
27
- > [!NOTE]
28
- > You can use both configuration methods simultaneously. Galbe will first apply the settings from `galbe.config.{js,ts}`, and any properties passed during instantiation will override the corresponding ones from the configuration file.
29
-
30
- ## Configuration Properties
31
-
32
- ### hostname
33
- The hostname of the server. Default: `localhost`.
34
-
35
- ### port
36
- The port number the server will listen on. Default: `3000`.
37
-
38
- ### basePath
39
- A base path added as a prefix to all routes.
40
-
41
- ### routes
42
- A glob pattern or list of glob patterns defining the route files to be analyzed by the [Automatic Route Analyzer](routes.md#automatic-route-analyzer). Default: `src/**/*.route.{js,ts}`.
43
-
44
- ### plugin
45
- A property used by plugins to add specific configurations. Each key should correspond to a [Unique Plugin Identifier](plugins.md).
46
-
47
- ### tls
48
- Enables or disables TLS support. Default: `false`.
49
- - **tls.key**: Path to the private key file.
50
- - **tls.cert**: Path to the certificate file.
51
- - **tls.ca**: Path to the certificate authority file.
52
-
53
- ### requestValidator.enabled
54
- Enables or disables _request_ schema validation (see [Request Schema Definition](schemas.md#request-schema-definition)). Default: `true`.
55
-
56
- ### responseValidator.enabled
57
- Enables or disables _response_ schema validation (see [Response Schema Definition](schemas.md#request-schema-definition#response)). Default: `true`.
58
-
59
- ## Config Type Safety
60
-
61
- To ensure type safety for your configuration, use the `config` helper method, which leverages your IDE’s IntelliSense:
62
-
63
- ```ts
64
- import { config } from "galbe"
65
-
66
- export default config({
67
- // ...
68
- })
69
- ```
70
-
71
- Alternatively, if you are using TypeScript, you can apply the `GalbeConfig` type to enforce type consistency:
72
-
73
- ```ts
74
- import type { GalbeConfig } from "galbe"
75
-
76
- export default {
77
- // ...
78
- } satisfies GalbeConfig
79
- ```
80
-
package/docs/context.md DELETED
@@ -1,104 +0,0 @@
1
- # Context
2
-
3
- An instance of the context object is created when a new request is initiated and is carried throughout the entire request lifecycle. See the [Lifecycle](https://galbe.dev/documentation/lifecycle) section for more details.
4
-
5
- Its purpose is to carry all relevant information about the request and facilitate data sharing between different stages of the request lifecycle.
6
-
7
- ## Definition
8
-
9
- A context object has the following properties:
10
-
11
- ### request
12
-
13
- An instance of the [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object created by the server.
14
-
15
- ### headers
16
-
17
- A JavaScript object representing the headers of the current request.
18
-
19
- - **key** (string): Header name
20
- - **value** (string | [schema defined](schemas.md#headers)): Header value
21
-
22
- ### params
23
-
24
- A JavaScript object representing the route parameters of the current request.
25
-
26
- - **key** (string): Parameter name
27
- - **value** (string | [schema defined](schemas.md#params)): Parameter value
28
-
29
- ```js
30
- galbe.get('/default/:p1/foo/:p2', ctx => console.log(ctx.params))
31
- // GET /default/four/foo/2
32
- { p1: "four", p2: "2" }
33
- ```
34
-
35
- ### query
36
-
37
- A JavaScript object representing the query parameters of the current request.
38
-
39
- - **key** (string): Query parameter name
40
- - **value** (string | [schema defined](schemas.md#query)): Query parameter value
41
-
42
- ```js
43
- galbe.get('/test', ctx => console.log(ctx.query))
44
- // GET /test?one=1&two=2
45
- { one: "1", two: "2" }
46
- ```
47
-
48
- ### body
49
-
50
- The body payload of the incoming request. The body type is determined based on the following rules:
51
-
52
- If no [Schema](schemas.md) is defined, Galbe will parse the body type according to the `content-type` header:
53
-
54
- - `text/.*`: string
55
- - `application/json`: object
56
- - `application/x-www-form-urlencoded`: `{ [key: string]: any }`
57
- - `multipart/form-data`: `{ [key: string]: { headers: { name: string; type?: string; filename?: string }; content: any } }`
58
- - `other`: `AsyncGenerator<Uint8Array>`
59
-
60
- If a [Schema](schemas.md) is defined, Galbe will parse the body according to the [Schema.body](schemas.md#body) definition for the current route.
61
-
62
- ### set
63
-
64
- The `set` property contains modifiable attributes intended to provide information to the response parser.
65
-
66
- - **status**: Sets the response status.
67
- - **headers**: Sets the response headers.
68
-
69
- ```js
70
- galbe.get('/example', ctx => {
71
- ctx.set.status = 418;
72
- return "I don't do coffee";
73
- })
74
- ```
75
-
76
- ### state
77
-
78
- The `state` property allows storing custom user-defined objects throughout the request lifecycle. It is commonly used to share data between [hooks](hooks.md) and the [handler](handler.md).
79
-
80
- - **key** (string): User-defined key
81
- - **value** (any): User-defined object
82
-
83
- ```js
84
- galbe.get(
85
- '/example',
86
- [
87
- ctx => {
88
- ctx.state['foo'] = 'bar';
89
- }
90
- ],
91
- ctx => {
92
- return ctx.state.foo;
93
- }
94
- )
95
- ```
96
-
97
- ```bash
98
- $ curl http://localhost:3000/example
99
- bar
100
- ```
101
-
102
- ### remoteAddress
103
-
104
- An instance of [SocketAddress](https://github.com/oven-sh/bun/blob/fe62a614046948ebba260bed87db96287e67921f/packages/bun-types/bun.d.ts#L2600-L2613) representing the remote address of the client.
@@ -1,54 +0,0 @@
1
- # Error Handler
2
-
3
- Any error occurring during a request lifecycle is intercepted by the error handler.
4
-
5
- You can customize the default error-handling behavior by defining a custom error handler using Galbe's instance `onError` method.
6
-
7
- ```js
8
- const galbe = new Galbe()
9
- galbe.onError(customErrorHandler)
10
- ```
11
-
12
- ## Definition
13
-
14
- The error handler should be a function that takes two arguments: an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) and a [Context](context.md). This function may return a [Response type](handler.md#response-types).
15
-
16
- ```js
17
- galbe.onError((error, ctx) => {
18
- if (error.status === 500) {
19
- return new Response(`Server error ❌`, { status: 500 })
20
- }
21
- if (error.status === 404) {
22
- return new Response(`Not found 🔎`, { status: 404 })
23
- }
24
- })
25
- ```
26
-
27
- The `error` argument can be any type of error thrown by your application. If the error originates from the Galbe framework, it will be an instance of [RequestError](#request-error).
28
-
29
- For example, the [Router](router.md) will throw a `RequestError` with a `404` status if no route matches the incoming request path. Similarly, the parser will throw a `RequestError` with a `400` status in case of invalid input.
30
-
31
- ## Request Error
32
-
33
- The `RequestError` class is used to instantiate a runtime request error in Galbe. It has three optional attributes: `status`, `payload`, and `headers`.
34
-
35
- If your application throws a `RequestError` instance, Galbe will, by default, construct a Response from your `RequestError` and send it back to the client.
36
-
37
- ```js
38
- import { RequestError } from 'galbe'
39
-
40
- galbe.get('/coffee', () => {
41
- throw new RequestError({ status: 418, payload: '🫖' })
42
- })
43
- ```
44
-
45
- When called, the above endpoint should respond:
46
-
47
- ```bash
48
- $ curl -i http://localhost:3000/coffee
49
- HTTP/1.1 418 I'm a Teapot
50
- Content-Type: application/json
51
- Content-Length: 6
52
-
53
- 🫖
54
- ```