Handler
For routing is to tell which function to return a response to.
The function for returning a Response is Handler
.
Handler is a callback function which accept Context
, helping you access powerful API for accessing data and modifying the response.
The params
from the previous example also come from Handler
// Structure
app.get(path, handler, hook?)
// Usage
app.get('/id/:id', (context) => context.params.id)
// Structure
app.get(path, handler, hook?)
// Usage
app.get('/id/:id', (context) => context.params.id)
Context
Context's properties consists of
request
: RawRequest
for accessing data as web standard typebody
: Body which come with the requestquery
: Parsed path query as a simple objectparams
: Path parameters as a simple objectstore
: A global mutable store for Elysia instanceset
: Response representationstatus
: response statusheaders
: response headersredirect
: redirect to new path
You can access Context
in Handler
function:
app.post('/', ({ body, set }) => {
const signed = signIn(body)
if(signed)
return 'Welcome back'
set.status = 403
return 'Invalid username or password'
})
app.post('/', ({ body, set }) => {
const signed = signIn(body)
if(signed)
return 'Welcome back'
set.status = 403
return 'Invalid username or password'
})
TIP
Elysia encourages object destructuring, but set
is an exception. As destructured primitive value is not linked to the object, in order to make set
work properly, we need to use set.value
Response
Returning value from Handler
, Elysia will try to map returned value into Response
.
For eaxmple, to return an object, you should stringify the content first and then set response header of Content-Type
to application/json
.
Which look something like this:
new Response(JSON.stringify({
'vtuber': [
'Shirakami Fubuki',
'Inugami Korone'
]
}, {
headers: {
'Content-Type': 'application/json'
}
})
new Response(JSON.stringify({
'vtuber': [
'Shirakami Fubuki',
'Inugami Korone'
]
}, {
headers: {
'Content-Type': 'application/json'
}
})
But Elysia handle that for you.
You simply return an object, and Elysia will map your value to a correct response for you.
app.get('/', () => ({
'vtuber': [
'Shirakami Fubuki',
'Inugami Korone'
]
}))
app.get('/', () => ({
'vtuber': [
'Shirakami Fubuki',
'Inugami Korone'
]
}))
Ofcourse, as Elysia map the value to Response
.
But you can also return a Response
if you really want to.
app.get('/', () => new Response(
JSON.stringify({
'vtuber': [
'Shirakami Fubuki',
'Inugami Korone'
]
}, {
headers: {
'Content-Type': 'application/json'
}
})
)
app.get('/', () => new Response(
JSON.stringify({
'vtuber': [
'Shirakami Fubuki',
'Inugami Korone'
]
}, {
headers: {
'Content-Type': 'application/json'
}
})
)