localhost
GET
One of the most important areas to create a secure web server is to make sure that requests are in the correct shape.
Elysia handled this by providing a validation tool out of the box to validate incoming requests using Schema Builder.
Elysia.t, a schema builder based on TypeBox to validate the value in both runtime and compile-time, providing type safety like in a strict type language.
Elysia schema can validate the following:
Schema can be categorized into 2 types:
The local schema is executed on a specific route.
To validate a local schema, you can inline schema into a route handler:
import { Elysia, t } from 'elysia'
new Elysia()
.get('/id/:id', ({ params: { id } }) => id, {
params: t.Object({
id: t.Numeric()
})
})
.listen(3000)
GET
This code ensures that our path parameter id, will always be a numeric string and then transform to a number automatically in both runtime and compile-time (type-level).
The response should be listed as follows:
Path | Response |
---|---|
/id/1 | 1 |
/id/a | Error |
Register hook into every handler that came after.
To add a global hook, you can use .guard
followed by a life cycle event in camelCase:
import { Elysia, t } from 'elysia'
new Elysia()
.get('/none', () => 'hi')
.guard({
query: t.Object({
name: t.String()
})
})
.get('/query', ({ query: { name } }) => name)
.get('/any', ({ query }) => query)
.listen(3000)
This code ensures that the query must have name with a string value for every handler after it. The response should be listed as follows:
GET
The response should be listed as follows:
Path | Response |
---|---|
/none | hi |
/none?name=a | hi |
/query | error |
/query?name=a | a |
If multiple global schemas are defined for same property, the latest one will have the preference. If both local and global schemas are defined, the local one will have the preference.