Guard
When you need to apply multiple hooks to your application, instead of repeating hooks multiple times, you can use guard to bulk add hooks to your application.
import { Elysia, t } from 'elysia'
.onBeforeHandle(({ query: { name }, status }) => {
if(!name) return status(401)
.onBeforeHandle(({ query: { name } }) => {
.onAfterResponse(({ responseValue }) => {
console.log(responseValue)
({ query: { name }, status }) => {
if(!name) return status(401)
({ query: { name } }) => {
afterResponse({ responseValue }) {
console.log(responseValue)
}, ({ query: { name = 'anon' } }) => `Hello ${name}!`
}, ({ query: { name = 'anon' } }) => `Hello ${name}!`
Not only that, you can also apply schema to multiple routes using guard.
import { Elysia, t } from 'elysia'
({ query: { name }, status }) => {
if(!name) return status(401)
({ query: { name } }) => {
afterResponse({ responseValue }) {
console.log(responseValue)
}, ({ query: { name = 'anon' } }) => `Hello ${name}!`
}, ({ query: { name = 'anon' } }) => `Hello ${name}!`
This will apply hooks and schema to every route after .guard is called in the same instance.
See Guard for more information.
Assignment
Let’s put 2 types of hooks into practice.