Skip to content

Commit bd34466

Browse files
committed
📘 doc(docs): hook type
1 parent 1821022 commit bd34466

File tree

1 file changed

+44
-10
lines changed

1 file changed

+44
-10
lines changed

docs/essential/life-cycle.md

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -190,31 +190,65 @@ Console should log as the following:
190190
```
191191

192192
## Hook type
193-
Starting from Elysia 1.0 Elysia will treat hook at local first.
193+
Starting from Elysia 1.0 introduce a **hook type**, to specify if the hook should be local-only, or global.
194194

195-
If a hook is register on an instance, it will only apply to itself and descendants only.
195+
Elysia hook type are as the following:
196+
- local (default) - apply to only current instance and descendant only
197+
- scoped - apply to only 1 ascendant, current instance and descendants
198+
- global - apply to all instance that apply the plugin (all ascendants, current, and descendants)
196199

200+
If not specified, hook is local by default.
201+
202+
::: tip
203+
Starting from Elysia 1.0 hook is local by default while Elysia < 1.0 will be global only.
204+
205+
This is a breaking change.
206+
:::
207+
208+
To specify hook's type, add a `{ as: hookType }` to hook.
209+
210+
To apply hook to globally, we need to specify hook as global.
197211
```typescript
198212
const plugin = new Elysia()
199-
.onBeforeHandle(() => {
213+
.onBeforeHandle(() => { // [!code --]
214+
.onBeforeHandle({ as: 'global' }, () => { // [!code ++]
200215
console.log('hi')
201216
})
202217
.get('/child', () => 'log hi')
203218

204219
const main = new Elysia()
205220
.use(plugin)
206-
.get('/parent', () => 'not log hi')
221+
.get('/parent', () => 'log hi')
207222
```
208223
209-
To apply hook to globally, we need to specify hook as global.
224+
Let's create a plugin to illustrate how hook type work.
225+
210226
```typescript
211-
const plugin = new Elysia()
212-
.onBeforeHandle({ as: 'global' }, () => {
227+
// ? Value base on table value provided below
228+
const type = 'local'
229+
230+
const child = new Elysia()
231+
.get('/child', () => 'hello')
232+
233+
const current = new Elysia()
234+
.onBeforeHandle({ as: type }, () => {
213235
console.log('hi')
214236
})
215-
.get('/child', () => 'log hi')
237+
.get('/child', () => 'hello')
238+
239+
const parent = new Elysia()
240+
.use(current)
241+
.get('/parent', () => 'hello')
216242

217243
const main = new Elysia()
218-
.use(plugin)
219-
.get('/parent', () => 'log hi')
244+
.use(parent)
245+
.get('/main', () => 'hello')
220246
```
247+
248+
By changing the `type` value, the result should be as follows:
249+
250+
| type | child | current | parent | main |
251+
| ---------- | ----- | ------- | ------ | ---- |
252+
| 'local' | ✅ | ✅ | ❌ | ❌ |
253+
| 'scope' | ✅ | ✅ | ✅ | ❌ |
254+
| 'global' | ✅ | ✅ | ✅ | ✅ |

0 commit comments

Comments
 (0)