Macro
Macro is similar to a function that has control over the lifecycle event, schema, context with full type safety.
Once defined, it will be available in a hook and can be activated by adding the property.
import { Elysia } from 'elysia'
const plugin = new Elysia({
name: 'plugin'
}).macro({
hi: (word: string) => ({
beforeHandle() {
console.log(word)
}
})
})
const app = new Elysia()
.use(plugin)
.get('/', () => 'hi', {
hi: 'Elysia'
})
Accessing the path should log “Elysia” as the results.
Property shorthand
Starting from Elysia 1.2.10, each property in the macro object can be a function or an object.
If the property is an object, it will be translated to a function that accepts a boolean parameter, and will be executed if the parameter is true.
import { Elysia } from 'elysia'
export const auth = new Elysia()
.macro({
// This property shorthand
isAuth: {
resolve: () => ({
user: 'saltyaom'
})
},
// is equivalent to
isAuth(enabled: boolean) {
if (!enabled) return
return {
resolve() {
return { user }
}
}
}
})
API
macro has the same API as a hook.
In the previous example we create a hi macro that accepts a string.
We then assigned hi to "Elysia", the value was then sent back to the hi function, and then that function added a new event to the beforeHandle stack.
This is equivalent to pushing a function to beforeHandle as follows:
import { Elysia } from 'elysia'
const app = new Elysia()
.get('/', () => 'hi', {
beforeHandle() {
console.log('Elysia')
}
})
macro shines when a logic is more complex than simply accepting a new function—for example, creating an authorization layer for each route.
import { Elysia } from 'elysia'
import { auth } from './auth'
const app = new Elysia()
// …
The code snippet above is truncated.