@@ -190,31 +190,65 @@ Console should log as the following:
190
190
```
191
191
192
192
## 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 .
194
194
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)
196
199
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.
197
211
``` typescript
198
212
const plugin = new Elysia ()
199
- .onBeforeHandle (() => {
213
+ .onBeforeHandle (() => { // [!code --]
214
+ .onBeforeHandle ({ as: ' global' }, () => { // [!code ++]
200
215
console .log (' hi' )
201
216
})
202
217
.get (' /child' , () => ' log hi' )
203
218
204
219
const main = new Elysia ()
205
220
.use (plugin )
206
- .get (' /parent' , () => ' not log hi' )
221
+ .get (' /parent' , () => ' log hi' )
207
222
` ` `
208
223
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
+
210
226
` ` ` 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 }, () => {
213
235
console .log (' hi' )
214
236
})
215
- .get (' /child' , () => ' log hi' )
237
+ .get (' /child' , () => ' hello' )
238
+
239
+ const parent = new Elysia ()
240
+ .use (current )
241
+ .get (' /parent' , () => ' hello' )
216
242
217
243
const main = new Elysia ()
218
- .use (plugin )
219
- .get (' /parent ' , () => ' log hi ' )
244
+ .use (parent )
245
+ .get (' /main ' , () => ' hello ' )
220
246
` ` `
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