State and Decorate
You can extend Elysia to fit your need. This is useful when you need to access extra values in a handler (e.g. a database connection).
In summary:
state
: assign value toContext.store
(a global state object of the Elysia instance)decorate
: assign value toContext
TIP
Context
is a parameter in the callback of handler.
Example
typescript
app
.state('version', 1)
.decorate('getDate', () => Date.now())
.get('/version', ({
getDate,
store: { version }
}) => `${version} ${getDate()}`
)
app
.state('version', 1)
.decorate('getDate', () => Date.now())
.get('/version', ({
getDate,
store: { version }
}) => `${version} ${getDate()}`
)
version
is registered usingstate
, and accessible viaContext.store.version
.getDate
is registered usingdecorate
, and accessible viaContext.getDate
.
TypeScript
You can type state and decorator explictly using TypeScript with as
:
typescript
app
// Will type version as `number | null`
.state('version', 1 as number | null)
.get('/version', ({
store: { version }
}) => version
app
// Will type version as `number | null`
.state('version', 1 as number | null)
.get('/version', ({
store: { version }
}) => version
If explictly typed doesn't type null
or undefined
, make sure to set strict
to true
in tsconfig.json
:
json
// tsconfig.json
{
"compilerOptions": {
"strict": true
}
}
// tsconfig.json
{
"compilerOptions": {
"strict": true
}
}