Skip to content

Commit

Permalink
docs: add final documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Romakita committed Nov 28, 2024
1 parent 721b10a commit f324c22
Show file tree
Hide file tree
Showing 6 changed files with 437 additions and 23 deletions.
1 change: 1 addition & 0 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export default defineConfig({
text: "Introduction",
items: [
{text: "What is Ts.ED?", link: "/introduction/what-is-tsed"},
{text: "What's new in v8?", link: "/introduction/what-is-news-v8"},
{text: "Capabilities", link: "/introduction/capabilities"},
{text: "Installation", link: "/introduction/getting-started"},
{text: "Create your first controller", link: "/introduction/create-your-first-controller"}
Expand Down
Binary file added docs/docs/assets/hooks-v8.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 11 additions & 0 deletions docs/docs/assets/hooks-v8.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
209 changes: 186 additions & 23 deletions docs/docs/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ when they occur.

This schema resume the order of hooks regard to the providers:

![hook in sequence](./assets/hooks-in-sequence.png)
[![hooks](./assets/hooks-v8.png)](./assets/hooks-v8.png)

Here is the related code described by the previous schema:

Expand Down Expand Up @@ -55,6 +55,16 @@ class Server implements BeforeInit {
}
```

Since v8, it's possible to use `@tsed/hooks` package to subscribe to hooks:

```typescript
import {$on} from "@tsed/hooks";

$on("$beforeInit", () => {
// do something
});
```

### Module / Service

You can subscribe to a hook in your @@Module@@ or @@Service@@:
Expand All @@ -68,30 +78,20 @@ export class MyModule implements OnInit {
}
```

::: tip Note
Database connection can be performed with Asynchronous Provider. See [custom providers](/docs/custom-providers)
:::

### $onRequest/$onResponse

Ts.ED provide a way to intercept the request and response event. You can listen these hooks by implementing a `$onRequest` and `$onResponse` methods
on an injectable service:
Since v8, it's possible to use `@tsed/hooks` package to subscribe to hooks:

```typescript
import {Module} from "@tsed/di";
import {PlatformContext} from "@tsed/platform-http";
import {$on} from "@tsed/hooks";

@Module()
class CustomContextModule {
$onRequest($ctx: PlatformContext) {
// do something
}
$onResponse($ctx: PlatformContext) {
// do something
}
}
$on("$onInit", () => {
// do something
});
```

::: tip Note
Database connection can be performed with Asynchronous Provider. See [custom providers](/docs/custom-providers)
:::

### Custom provider

It's also possible to subscribe to a hook in a [custom provider](/docs/custom-providers):
Expand Down Expand Up @@ -122,7 +122,8 @@ It's now easy to close database connection through the `hooks` methods!
Emit event let the developers subscribe and implement his tasks.

```ts
import {Module, $emit} from "@tsed/di";
import {Module} from "@tsed/di";
import {$asyncEmit} from "@tsed/hooks";

export interface OnEvent {
$myEvent(value: string): Promise<void>;
Expand All @@ -133,7 +134,7 @@ export class ModuleEmitter {
async initSomething() {
// do something before

await $emit("$myEvent"); // emit accept extra parameters forwarded to subscribers
await $asyncEmit("$myEvent"); // emit accept extra parameters forwarded to subscribers

// do something after
}
Expand All @@ -156,7 +157,8 @@ export class ModuleSubscriber extends OnEvent {

## Alterable value event

This feature let you emit an event with a value. All providers who subscribe to it can modify the value passed as a parameter and return a new value which will be passed to the next provider.
This feature let you emit an event with a value. All providers who subscribe to it can modify the value passed as a
parameter and return a new value which will be passed to the next provider.

```ts
// module-emitter
Expand Down Expand Up @@ -191,3 +193,164 @@ export class ModuleSubscriber extends AlterEvent {
}
}
```

## Listen token invocation

`$beforeInvoke` and `$afterInvoke` allow you to perform some actions before and after the invocation of the injectable class/factory/async factory.

These hooks can be listened for all tokens or for a specific token:

```typescript
import type {TokenProvider, ResolvedInvokeOptions} from "@tsed/di";
import {$on} from "@tsed/hooks";

// triggered for all tokens
$on("$beforeInvoke", (token: TokenProvider, resolvedOpts: ResolvedInvokeOptions) => {
// do something
});

// triggered for a specific token

@Injectable()
class MyService {}

$on("$beforeInvoke", MyService, (token: TokenProvider, resolvedOpts: ResolvedInvokeOptions) => {
// do something
console.log(token === MyService); // true
});
```

Here is the same example with `$afterInvoke`:

```typescript
import type {TokenProvider, ResolvedInvokeOptions} from "@tsed/di";
import {$on} from "@tsed/hooks";

// triggered for all tokens
$on("$afterInvoke", (instance: unknown, resolvedOpts: ResolvedInvokeOptions) => {
// do something
});

@Injectable()
class MyService {}

$on("$afterInvoke", MyService, (instance: MyService, resolvedOpts: ResolvedInvokeOptions) => {
// do something
console.log(resolvedOpts.token === MyService); // true
console.log(instance instanceof MyService); // true
});
```

## Listen token instantiation by type

`$beforeInit:${type}` can be used to observe the instantiation of a specific @@ProviderType@@.
Currently, Ts.ED framework use this event to build the controller router and attach the router as following:

```typescript
import type {ResolvedInvokeOptions} from "@tsed/di";
import {$on} from "@tsed/hooks";

$on(`$beforeInvoke:${ProviderType.CONTROLLER}`, ({provider, locals}: ResolvedInvokeOptions) => {
const router = createInjectableRouter(provider as ControllerProvider);
locals.set(PlatformRouter, router);
});
```

By using this event, Ts.ED attach a router to the controller provider. This action,
let the developer the ability to inject the router in the controller constructor:

```typescript
import {Controller} from "@tsed/di";
import {PlatformRouter} from "@tsed/platform-router";

@Controller("/")
export class MyController {
constructor(private router: PlatformRouter) {}
}
```

## $onInit

The `$onInit` hook is called when all token are resolved by the `injector.load()`.
It's the right place to perform asynchronous tasks when you use a class as injectable token.

```typescript
import {Module, OnInit} from "@tsed/di";

@Module()
export class MyModule implements OnInit {
cachedData: any;

async $onInit(): Promise<any> {
this.cachedData = await this.loadData();
}
}
```

We recommend to use async provider to perform asynchronous tasks. See [custom providers](/docs/custom-providers).

## $onDestroy

The `$onDestroy` hook is called when the provider instance is destroyed. It's the right place to perform cleanup tasks.

```typescript
import {Module, OnDestroy} from "@tsed/di";

@Module()
export class MyModule implements OnDestroy {
async $onDestroy(): Promise<any> {
await this.closeConnection();
}
}
```

## $onRequest and $onResponse

Ts.ED provide a way to intercept the request and response event. You can listen these hooks by implementing a
`$onRequest` and `$onResponse` methods
on an injectable service:

```typescript
import {Module} from "@tsed/di";
import {PlatformContext} from "@tsed/platform-http";

@Module()
class CustomContextModule {
$onRequest($ctx: PlatformContext) {
// do something
}

$onResponse($ctx: PlatformContext) {
// do something
}
}
```

Since v8, it's possible to use `@tsed/hooks` package to subscribe to hooks:

```typescript
import {$on} from "@tsed/hooks";

$on("$onRequest", ($ctx: PlatformContext) => {
// do something
});

$on("$onResponse", ($ctx: PlatformContext) => {
// do something
});
```

## $onReady

The `$onReady` hook is called when the server is ready to accept incoming requests.

```typescript
import {Module, OnReady} from "@tsed/di";

@Module()
export class MyModule implements OnReady {
async $onReady(): Promise<any> {
// do something
}
}
```
4 changes: 4 additions & 0 deletions docs/introduction/migrate-from-v7.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@ include support for [Apollo 4](/tutorials/graphql.html#apollo), the removal of C
[ECMAScript Modules](#switch-your-code-base-on-esm), enhanced [request logging](#request-logger-doesn-t-work), and additional [optimizations](#optimization)
to reduce code size.

We also re-think the hooks features be more useful and easier to use.
Now, you can use the [`@tsed/hooks`](/docs/hooks) package to subscribe to hooks outside the DI context.

Additionally, some deprecated methods and packages were removed or updated to be aligned with new DI functions (aka [Functional API](/docs/providers.md)).
For further details, you can view the full release notes here.

| Topics | Migration note | Issue |
| -------------------------------------------------------------------------- | ------------------------------------- | --------------------------------------------------------------------- |
| Access to injector instance everywhere | [See](#injector-instance-everywhere) | [#2812](https://github.com/tsedio/tsed/pull/2812) |
| `useDefineForClassFields` must be set to false | [See](#usedefineforclassfields) | [#2814](https://github.com/tsedio/tsed/pull/2814) |
| Add `@tsed/hooks` package to listen and emit events | [See](/docs/hooks) | [rc.6](https://github.com/tsedio/tsed/releases/tag/v8.0.0-rc.6) |
| Remove proxy on DI Configuration | [See](#use-configuration-get-method) | [beta.6](https://github.com/tsedio/tsed/releases/tag/v8.0.0-beta.6) |
| Removal of CommonJS support | [See](#switch-your-code-base-on-esm) | [alpha.6](https://github.com/tsedio/tsed/releases/tag/v8.0.0-alpha.6) |
| Apollo Server v4 support | [See](/tutorials/graphql.html#apollo) | [#2493](https://github.com/tsedio/tsed/issues/2493) |
Expand Down
Loading

0 comments on commit f324c22

Please sign in to comment.