|
| 1 | +--- |
| 2 | +title: State and Decorate - ElysiaJS |
| 3 | +head: |
| 4 | + - - meta |
| 5 | + - property: 'og:title' |
| 6 | + content: State and Decorate - ElysiaJS |
| 7 | + |
| 8 | + - - meta |
| 9 | + - name: 'description' |
| 10 | + content: You can extend Elysia to fits your need with ".state" and ".decorate" to add custom value to the "Context", and handler, for example. Database connection, utility function, or cookie. |
| 11 | + |
| 12 | + - - meta |
| 13 | + - property: 'og:description' |
| 14 | + content: You can extend Elysia to fits your need with ".state" and ".decorate" to add custom value to the "Context", and handler, for example. Database connection, utility function, or cookie. |
| 15 | +--- |
| 16 | + |
| 17 | +# State and Decorate |
| 18 | +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). |
| 19 | + |
| 20 | +In summary: |
| 21 | +- `state`: assign value to `Context.store` (a global state object of the Elysia instance) |
| 22 | +- `decorate`: assign value to `Context` |
| 23 | + |
| 24 | +::: tip |
| 25 | +`Context` is a parameter in the callback of handler. |
| 26 | +::: |
| 27 | + |
| 28 | +### Example |
| 29 | + |
| 30 | +```typescript |
| 31 | +app |
| 32 | + .state('version', 1) |
| 33 | + .decorate('getDate', () => Date.now()) |
| 34 | + .get('/version', ({ |
| 35 | + getDate, |
| 36 | + store: { version } |
| 37 | + }) => `${version} ${getDate()}`) |
| 38 | +``` |
| 39 | + |
| 40 | +- `version` is registered using `state`, and accessible via `Context.store.version`. |
| 41 | +- `getDate` is registered using `decorate`, and accessible via `Context.getDate`. |
| 42 | + |
| 43 | +## Remap |
| 44 | +By providing a function as a first parameters, the callback will accept current value, allowing us to remap the value to anything we like. |
| 45 | + |
| 46 | +```typescript |
| 47 | +app |
| 48 | + .state({ |
| 49 | + a: "a", |
| 50 | + b: "b" |
| 51 | + }) |
| 52 | + // Exclude b state |
| 53 | + .state(({ b, ...rest }) => rest) |
| 54 | + .get('/version', ({ |
| 55 | + store: { a } |
| 56 | + }) => a) |
| 57 | +``` |
| 58 | + |
| 59 | +## TypeScript |
| 60 | +You can type state and decorator explicitly using TypeScript with `as`: |
| 61 | +```typescript |
| 62 | +app |
| 63 | + // Will type version as `number | null` |
| 64 | + .state('version', 1 as number | null) |
| 65 | + .get('/version', ({ |
| 66 | + store: { version } |
| 67 | + }) => version) |
| 68 | +``` |
| 69 | + |
| 70 | +If the explicit type doesn't type `null` or `undefined`, make sure to set `strict` to `true` in `tsconfig.json`: |
| 71 | +```json |
| 72 | +// tsconfig.json |
| 73 | +{ |
| 74 | + "compilerOptions": { |
| 75 | + "strict": true |
| 76 | + } |
| 77 | +} |
| 78 | +``` |
0 commit comments