raiton 5.9.4-beta.15 → 5.9.7-beta.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/index.mjs +3 -1
- package/docs/README.md +136 -0
- package/docs/cli/README.md +81 -0
- package/docs/cli/commands.md +167 -0
- package/docs/cli/hmr.md +121 -0
- package/docs/core/README.md +67 -0
- package/docs/core/application.md +149 -0
- package/docs/core/builder-thread.md +231 -0
- package/docs/core/config.md +124 -0
- package/docs/core/controller.md +120 -0
- package/docs/core/injection.md +226 -0
- package/docs/core/middleware.md +172 -0
- package/docs/core/plugin-scope.md +171 -0
- package/docs/core/router.md +122 -0
- package/docs/framework/README.md +96 -0
- package/docs/framework/base-classes.md +214 -0
- package/docs/framework/decorators/README.md +60 -0
- package/docs/framework/decorators/controllable.md +151 -0
- package/docs/framework/decorators/injection.md +186 -0
- package/docs/framework/decorators/middleware.md +167 -0
- package/docs/framework/decorators/openapi.md +254 -0
- package/docs/framework/decorators/parametrable.md +248 -0
- package/docs/framework/decorators/socket.md +152 -0
- package/docs/framework/encryption.md +183 -0
- package/docs/framework/env.md +88 -0
- package/docs/framework/plugins/README.md +50 -0
- package/docs/framework/plugins/body-parser.md +138 -0
- package/docs/framework/plugins/openapi.md +217 -0
- package/docs/framework/plugins/security.md +159 -0
- package/docs/framework/responses.md +180 -0
- package/docs/framework/runtime.md +138 -0
- package/docs/types/README.md +206 -0
- package/package.json +1 -1
- package/source/core/application.ts +2 -0
- package/source/core/router/handler.ts +2 -0
- package/source/framework/decorators/route-interaction.decorator.ts +1 -1
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
# Injection de Dépendances
|
|
2
|
+
|
|
3
|
+
**Fichier :** `source/core/injection/injection.ts`
|
|
4
|
+
**Import :** `import { Injection } from "raiton/core"`
|
|
5
|
+
|
|
6
|
+
> **Navigation :** [← controller.md](controller.md) | [↑ core/](README.md) | [plugin-scope.md →](plugin-scope.md)
|
|
7
|
+
|
|
8
|
+
Conteneur DI complet avec support singleton, transient, détection de dépendances circulaires et cycle de vie.
|
|
9
|
+
|
|
10
|
+
## Concepts
|
|
11
|
+
|
|
12
|
+
### Scopes de cycle de vie (`LifetimeEnum` de `@protorians/core`)
|
|
13
|
+
|
|
14
|
+
| Scope | Comportement |
|
|
15
|
+
|-------|-------------|
|
|
16
|
+
| `SINGLETON` | Une seule instance par scope (`Symbol`). Réutilisée à chaque résolution. |
|
|
17
|
+
| `TRANSIENT` | Nouvelle instance à chaque résolution. |
|
|
18
|
+
|
|
19
|
+
## Méthodes statiques
|
|
20
|
+
|
|
21
|
+
### `Injection.registry(name, construct, lifetime?, scope?)`
|
|
22
|
+
|
|
23
|
+
Enregistrer une classe dans le conteneur :
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { Injection } from "raiton/core"
|
|
27
|
+
import { LifetimeEnum } from "@protorians/core"
|
|
28
|
+
|
|
29
|
+
// Singleton (par défaut)
|
|
30
|
+
Injection.registry("database", DatabaseService, LifetimeEnum.SINGLETON)
|
|
31
|
+
|
|
32
|
+
// Transient — nouvelle instance à chaque fois
|
|
33
|
+
Injection.registry("mailer", MailService, LifetimeEnum.TRANSIENT)
|
|
34
|
+
|
|
35
|
+
// Avec scope personnalisé
|
|
36
|
+
const adminScope = Symbol("admin")
|
|
37
|
+
Injection.registry("config", AppConfig, LifetimeEnum.SINGLETON, adminScope)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### `Injection.get(name, scope?)`
|
|
41
|
+
|
|
42
|
+
Résoudre une dépendance :
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
const db = Injection.get<DatabaseService>("database")
|
|
46
|
+
const config = Injection.get<AppConfig>("config", adminScope)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### `Injection.has(name)`
|
|
50
|
+
|
|
51
|
+
Vérifier si une dépendance est enregistrée :
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
if (Injection.has("database")) {
|
|
55
|
+
const db = Injection.get("database")
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### `Injection.resolve(construct)`
|
|
60
|
+
|
|
61
|
+
Résoudre une dépendance à partir du constructeur (utilise les métadonnées `@Injectable`) :
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
const controller = Injection.resolve(UserController)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### `Injection.clear()`
|
|
68
|
+
|
|
69
|
+
Vider le conteneur :
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
Injection.clear() // Vide classes, instances, dépendants et chemins d'artifacts
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### `Injection.shutdown()`
|
|
76
|
+
|
|
77
|
+
Arrêter le conteneur : appelle `onUnmount()` sur toutes les instances, puis `clear()`.
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
await Injection.shutdown()
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Décorateurs
|
|
84
|
+
|
|
85
|
+
### `@Injectable(lifetime?, name?, scope?)`
|
|
86
|
+
|
|
87
|
+
Enregistre automatiquement une classe dans le conteneur DI :
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
import { Injectable } from "raiton/framework"
|
|
91
|
+
import { LifetimeEnum } from "@protorians/core"
|
|
92
|
+
|
|
93
|
+
@Injectable(LifetimeEnum.SINGLETON, "myService")
|
|
94
|
+
class MyService {
|
|
95
|
+
getData() { return "data" }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Équivalent à :
|
|
99
|
+
Injection.registry("myService", MyService, LifetimeEnum.SINGLETON)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Si `name` est omis, le nom de la classe est utilisé (en camelCase).
|
|
103
|
+
|
|
104
|
+
### `@Inject(token?)`
|
|
105
|
+
|
|
106
|
+
Injecte une dépendance dans un paramètre du constructeur ou une propriété :
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
// Injection dans le constructeur
|
|
110
|
+
class UserService {
|
|
111
|
+
constructor(
|
|
112
|
+
@Inject() private db: DatabaseService,
|
|
113
|
+
@Inject("config") private config: AppConfig,
|
|
114
|
+
) {}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Injection dans une propriété
|
|
118
|
+
class UserController {
|
|
119
|
+
@Inject() private userService!: UserService
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
**Comportement :**
|
|
124
|
+
- Sans argument (`@Inject()`) : le type est déduit de `design:paramtypes` (constructeur) ou `design:type` (propriété).
|
|
125
|
+
- Avec argument (`@Inject("name")`) : résout par le nom donné.
|
|
126
|
+
|
|
127
|
+
## Résolution des dépendances
|
|
128
|
+
|
|
129
|
+
### Ordre de résolution des arguments
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
class MyService {
|
|
133
|
+
constructor(
|
|
134
|
+
@Inject() private db: DatabaseService, // 1. Token explicite via métadonnée
|
|
135
|
+
private config: AppConfig, // 2. design:paramtypes
|
|
136
|
+
private flag: boolean, // 3. undefined si non trouvé
|
|
137
|
+
) {}
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Détection des dépendances circulaires
|
|
142
|
+
|
|
143
|
+
```typescript
|
|
144
|
+
class A { constructor(@Inject() private b: B) {} }
|
|
145
|
+
class B { constructor(@Inject() private a: A) {} }
|
|
146
|
+
|
|
147
|
+
Injection.get("a")
|
|
148
|
+
// → Throwable: "Circular dependency detected: a -> b -> a"
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Cycle de vie des instances
|
|
152
|
+
|
|
153
|
+
Si une instance possède ces méthodes, elles sont automatiquement appelées :
|
|
154
|
+
|
|
155
|
+
| Méthode | Moment d'appel |
|
|
156
|
+
|---------|---------------|
|
|
157
|
+
| `onInit()` | Après création de l'instance (avant `onMount`) |
|
|
158
|
+
| `onMount()` | Après injection des propriétés |
|
|
159
|
+
| `onUnmount()` | Lors de `Injection.shutdown()` |
|
|
160
|
+
|
|
161
|
+
```typescript
|
|
162
|
+
@Injectable(LifetimeEnum.SINGLETON)
|
|
163
|
+
class DatabaseService {
|
|
164
|
+
private connection: any
|
|
165
|
+
|
|
166
|
+
onInit() {
|
|
167
|
+
console.log("DatabaseService initialisé")
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
onMount() {
|
|
171
|
+
this.connection = createConnection()
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async onUnmount() {
|
|
175
|
+
await this.connection.close()
|
|
176
|
+
console.log("DatabaseService fermé")
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Exemple complet
|
|
182
|
+
|
|
183
|
+
```typescript
|
|
184
|
+
import "reflect-metadata"
|
|
185
|
+
import { Injectable, Inject, Controllable, Get } from "raiton/framework"
|
|
186
|
+
|
|
187
|
+
// 1. Service — Singleton
|
|
188
|
+
@Injectable(LifetimeEnum.SINGLETON)
|
|
189
|
+
class UserRepository {
|
|
190
|
+
private users = [{ id: 1, name: "Alice" }]
|
|
191
|
+
|
|
192
|
+
findAll() { return this.users }
|
|
193
|
+
findById(id: number) { return this.users.find(u => u.id === id) }
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// 2. Contrôleur avec injection
|
|
197
|
+
@Controllable("/users")
|
|
198
|
+
export class UserController {
|
|
199
|
+
constructor(
|
|
200
|
+
@Inject() private repo: UserRepository
|
|
201
|
+
) {}
|
|
202
|
+
|
|
203
|
+
@Get("/")
|
|
204
|
+
list() {
|
|
205
|
+
return this.repo.findAll()
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
@Get("/:id")
|
|
209
|
+
get(@Param("id") id: string) {
|
|
210
|
+
return this.repo.findById(Number(id))
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
## Méthodes internes avancées
|
|
216
|
+
|
|
217
|
+
| Méthode | Usage |
|
|
218
|
+
|---------|-------|
|
|
219
|
+
| `updateConstruct(name, construct)` | Met à jour le constructeur d'une entrée (HMR) |
|
|
220
|
+
| `getDependents(name)` | Liste les dépendants directs d'une entrée |
|
|
221
|
+
| `registerArtifactPath(name, path)` | Enregistre le chemin d'un artifact |
|
|
222
|
+
| `getArtifactPath(name)` | Récupère le chemin d'un artifact |
|
|
223
|
+
|
|
224
|
+
---
|
|
225
|
+
|
|
226
|
+
[← controller.md](controller.md) | [↑ core/](README.md) | [plugin-scope.md →](plugin-scope.md)
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# Middleware
|
|
2
|
+
|
|
3
|
+
**Fichiers :** `source/core/middleware/`
|
|
4
|
+
**Import :** `import { middlewareCompose, MiddlewarePipeline } from "raiton/core"`
|
|
5
|
+
|
|
6
|
+
> **Navigation :** [← router.md](router.md) | [↑ core/](README.md) | [controller.md →](controller.md)
|
|
7
|
+
|
|
8
|
+
## `MiddlewarePipeline`
|
|
9
|
+
|
|
10
|
+
Pile de middleware exécutés séquentiellement dans l'ordre d'enregistrement (Koa-style).
|
|
11
|
+
|
|
12
|
+
```typescript
|
|
13
|
+
const pipeline = new MiddlewarePipeline()
|
|
14
|
+
|
|
15
|
+
// Ajouter un middleware
|
|
16
|
+
pipeline.use(async ({ context, next }) => {
|
|
17
|
+
console.log("Avant")
|
|
18
|
+
await next()
|
|
19
|
+
console.log("Après")
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
// Exécuter avec un gestionnaire final
|
|
23
|
+
await pipeline.run(ctx, finalHandler)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
### Signature d'un middleware
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
type MiddlewareType = (params: MiddlewareParametersInterface) => any
|
|
30
|
+
|
|
31
|
+
interface MiddlewareParametersInterface {
|
|
32
|
+
context: RequestContext // Contexte de la requête en cours
|
|
33
|
+
next: () => Promise<any> // Fonction pour passer au suivant
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**Règle impérative :** un middleware **doit** appeler `await next()` pour passer la main au middleware suivant. Sans cela, la chaîne est interrompue.
|
|
38
|
+
|
|
39
|
+
## `middlewareCompose`
|
|
40
|
+
|
|
41
|
+
Fonction de composition Koa-style. Utilisée en interne par `MiddlewarePipeline`.
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
44
|
+
const composed = middlewareCompose([mw1, mw2, mw3])
|
|
45
|
+
// Retourne une fonction (ctx) => Promise<any>
|
|
46
|
+
await composed(ctx)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Exemples
|
|
50
|
+
|
|
51
|
+
### Logger de temps d'exécution
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
app.use(async ({ context, next }) => {
|
|
55
|
+
const start = performance.now()
|
|
56
|
+
await next()
|
|
57
|
+
const duration = performance.now() - start
|
|
58
|
+
console.log(`${context.req.method} ${context.req.url} → ${duration.toFixed(2)}ms`)
|
|
59
|
+
})
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Authentification basique
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
app.use(async ({ context, next }) => {
|
|
66
|
+
const token = context.req.headers.get("authorization")
|
|
67
|
+
if (!token) {
|
|
68
|
+
context.reply.status(401)
|
|
69
|
+
return context.reply.send({ error: "Unauthorized" })
|
|
70
|
+
}
|
|
71
|
+
context.state.user = await verifyToken(token)
|
|
72
|
+
await next()
|
|
73
|
+
})
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Blocage d'IP
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
app.use(async ({ context, next }) => {
|
|
80
|
+
const ip = getRealIp(context.req)
|
|
81
|
+
if (blockedIps.includes(ip)) {
|
|
82
|
+
context.reply.status(403)
|
|
83
|
+
return context.reply.send({ error: "Forbidden" })
|
|
84
|
+
}
|
|
85
|
+
await next()
|
|
86
|
+
})
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Middleware sur une route spécifique (via décorateur)
|
|
90
|
+
|
|
91
|
+
```typescript
|
|
92
|
+
import { Controllable, Get, Middleware } from "raiton/framework"
|
|
93
|
+
|
|
94
|
+
const logger = async ({ context, next }) => {
|
|
95
|
+
console.log(`Route spécifique: ${context.req.url}`)
|
|
96
|
+
await next()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
@Controllable("/users")
|
|
100
|
+
export class UserController {
|
|
101
|
+
@Get("/:id")
|
|
102
|
+
@Middleware(logger) // ← middleware uniquement sur cette route
|
|
103
|
+
getById(@Param("id") id: string) {
|
|
104
|
+
return { id }
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Middleware sur tout un contrôleur
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
import { Controllable, Get, Middleware } from "raiton/framework"
|
|
113
|
+
|
|
114
|
+
const auth = async ({ context, next }) => {
|
|
115
|
+
if (!context.req.headers.get("authorization")) {
|
|
116
|
+
context.reply.status(401)
|
|
117
|
+
return
|
|
118
|
+
}
|
|
119
|
+
await next()
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
@Controllable("/admin")
|
|
123
|
+
@Middleware(auth) // ← middleware sur toutes les routes du contrôleur
|
|
124
|
+
export class AdminController {
|
|
125
|
+
@Get("/dashboard")
|
|
126
|
+
dashboard() {
|
|
127
|
+
return { sensitive: "data" }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## Ordre d'exécution
|
|
133
|
+
|
|
134
|
+
Les middlewares sont exécutés dans cet ordre :
|
|
135
|
+
|
|
136
|
+
1. **bodyParserPlugin** (enregistré automatiquement par `Application.initialize()`) → parse le body
|
|
137
|
+
2. **Security.headers** (enregistré automatiquement) → en-têtes de sécurité
|
|
138
|
+
3. **Middlewares des plugins** (ordre d'enregistrement)
|
|
139
|
+
4. **Middlewares globaux** (`app.use()`)
|
|
140
|
+
5. **Middleware du contrôleur** (`@Middleware` sur classe)
|
|
141
|
+
6. **Middleware de la route** (`@Middleware` sur méthode)
|
|
142
|
+
7. **Handler de la route**
|
|
143
|
+
|
|
144
|
+
## Pipeline et `RequestContext`
|
|
145
|
+
|
|
146
|
+
Le `RequestContext` traverse toute la chaîne et peut être enrichi via `context.state` :
|
|
147
|
+
|
|
148
|
+
```typescript
|
|
149
|
+
// Middleware 1 : authentification
|
|
150
|
+
app.use(async ({ context, next }) => {
|
|
151
|
+
context.state.user = { id: 1, role: "admin" }
|
|
152
|
+
await next()
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
// Middleware 2 : vérification de rôle
|
|
156
|
+
app.use(async ({ context, next }) => {
|
|
157
|
+
if (context.state.user.role !== "admin") {
|
|
158
|
+
context.reply.status(403)
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
await next()
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
// Handler
|
|
165
|
+
app.get("/admin/data", (ctx) => {
|
|
166
|
+
return { user: ctx.state.user, data: "secret" }
|
|
167
|
+
})
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
[← router.md](router.md) | [↑ core/](README.md) | [controller.md →](controller.md)
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# Système de Plugins
|
|
2
|
+
|
|
3
|
+
**Fichiers :** `source/core/plugins/`
|
|
4
|
+
**Import :** `import { definePlugin, PluginScope } from "raiton/core"`
|
|
5
|
+
|
|
6
|
+
> **Navigation :** [← injection.md](injection.md) | [↑ core/](README.md) | [config.md →](config.md)
|
|
7
|
+
|
|
8
|
+
## `PluginScope`
|
|
9
|
+
|
|
10
|
+
Chaque plugin reçoit un `PluginScope` qui lui donne accès isolé au routeur, au middleware et aux hooks. Les scopes enfants partagent leur parent. Voir `source/core/plugins/scope.ts`.
|
|
11
|
+
|
|
12
|
+
```typescript
|
|
13
|
+
class PluginScope {
|
|
14
|
+
hooks: HookStore // Hooks partagés avec le parent
|
|
15
|
+
middleware: MiddlewarePipeline // Pipeline partagé avec le parent
|
|
16
|
+
router: Router // Routeur partagé avec le parent
|
|
17
|
+
}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
### Méthodes
|
|
21
|
+
|
|
22
|
+
| Méthode | Description |
|
|
23
|
+
|---------|-------------|
|
|
24
|
+
| `use(mw)` | Ajoute un middleware. Si l'objet a une méthode `setup` avec 1 paramètre, il est traité comme un plugin. |
|
|
25
|
+
| `route(method, path, handler, version?)` | Ajoute une route |
|
|
26
|
+
| `get/post/put/patch/delete/options/head/trace(path, handler, version?)` | Raccourcis de routage |
|
|
27
|
+
| `register(plugin)` | Enregistre un sous-plugin dans un scope enfant |
|
|
28
|
+
| `addHook(name, fn)` | Ajoute un hook de cycle de vie |
|
|
29
|
+
|
|
30
|
+
### Fonctionnement de `register()` et `use()`
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
// Dans PluginScope :
|
|
34
|
+
|
|
35
|
+
register(plugin) {
|
|
36
|
+
// Si plugin.setup est une fonction à 1 paramètre :
|
|
37
|
+
const child = new PluginScope(this) // Scope enfant
|
|
38
|
+
plugin.setup(child) // Le plugin reçoit son scope isolé
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
use(mw) {
|
|
42
|
+
// Si l'objet a setup() à 1 paramètre → traité comme plugin
|
|
43
|
+
if (typeof mw === 'object' && 'setup' in mw && mw.setup.length === 1) {
|
|
44
|
+
mw.setup(this) // Middleware enregistré directement
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
// Sinon → middleware standard
|
|
48
|
+
this.middleware.use(mw)
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
**Règle :** un plugin a `setup(scope: PluginScope)` avec **1 paramètre**. Un middleware standard reçoit `({context, next})`.
|
|
53
|
+
|
|
54
|
+
### Propagation parent-enfant
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
const parent = new PluginScope() // hooks, middleware, router → nouveaux
|
|
58
|
+
const child = new PluginScope(parent) // hooks, middleware, router → ceux du parent
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Les scopes enfants **partagent** les mêmes références que le parent. Un middleware ajouté dans l'enfant est aussi visible du parent et vice-versa.
|
|
62
|
+
|
|
63
|
+
## `definePlugin`
|
|
64
|
+
|
|
65
|
+
Fonction utilitaire pour créer un plugin :
|
|
66
|
+
|
|
67
|
+
```typescript
|
|
68
|
+
import { definePlugin } from "raiton/core"
|
|
69
|
+
|
|
70
|
+
const monPlugin = definePlugin((scope) => {
|
|
71
|
+
scope.get("/status", () => ({ status: "ok" }))
|
|
72
|
+
}, "status-plugin")
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Exemples
|
|
76
|
+
|
|
77
|
+
### Plugin de télémétrie
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
const telemetryPlugin = {
|
|
81
|
+
name: "telemetry",
|
|
82
|
+
setup(scope: PluginScope) {
|
|
83
|
+
scope.use(async ({ context, next }) => {
|
|
84
|
+
const start = Date.now()
|
|
85
|
+
await next()
|
|
86
|
+
const duration = Date.now() - start
|
|
87
|
+
console.log(`${context.req.method} ${context.req.url} ${duration}ms`)
|
|
88
|
+
})
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
app.register(telemetryPlugin)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Plugin avec routes
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
const healthPlugin = {
|
|
99
|
+
name: "health",
|
|
100
|
+
setup(scope: PluginScope) {
|
|
101
|
+
scope.get("/health", () => ({ status: "ok", uptime: process.uptime() }))
|
|
102
|
+
scope.get("/health/db", async () => {
|
|
103
|
+
const db = Injection.get<DatabaseService>("database")
|
|
104
|
+
return { db: await db.ping() }
|
|
105
|
+
})
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
app.register(healthPlugin)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Plugin avec hooks
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
const maintenancePlugin = {
|
|
116
|
+
name: "maintenance",
|
|
117
|
+
setup(scope: PluginScope) {
|
|
118
|
+
scope.addHook("onRequest", (ctx) => {
|
|
119
|
+
if (isMaintenanceMode()) {
|
|
120
|
+
ctx.reply.status(503)
|
|
121
|
+
ctx.reply.send({ error: "Maintenance en cours" })
|
|
122
|
+
// Ne pas appeler next() → bloque la requête
|
|
123
|
+
}
|
|
124
|
+
})
|
|
125
|
+
},
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Sous-plugin dans un scope enfant
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
const parentPlugin = {
|
|
133
|
+
name: "parent",
|
|
134
|
+
setup(scope: PluginScope) {
|
|
135
|
+
scope.get("/parent", () => "parent")
|
|
136
|
+
|
|
137
|
+
// Sous-plugin isolé
|
|
138
|
+
scope.register({
|
|
139
|
+
name: "child",
|
|
140
|
+
setup(childScope: PluginScope) {
|
|
141
|
+
childScope.get("/child", () => "child")
|
|
142
|
+
},
|
|
143
|
+
})
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Composition de plusieurs plugins
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
app
|
|
152
|
+
.register(bodyParserPlugin()) // Plugin intégré
|
|
153
|
+
.register(healthPlugin) // Plugin perso
|
|
154
|
+
.register(openApiPlugin({ // Plugin OpenAPI
|
|
155
|
+
title: "Mon API",
|
|
156
|
+
endpoint: "/docs/json",
|
|
157
|
+
}))
|
|
158
|
+
.use(monMiddleware) // Middleware global
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Différence entre `register()` et `use()`
|
|
162
|
+
|
|
163
|
+
| Méthode | Usage | Comportement |
|
|
164
|
+
|---------|-------|-------------|
|
|
165
|
+
| `register(plugin)` | Plugin avec `setup(scope)` | Crée un scope enfant isolé |
|
|
166
|
+
| `use(plugin)` | Plugin avec `setup(scope)` (à 1 paramètre) | Utilise le scope courant |
|
|
167
|
+
| `use(mw)` | Middleware standard `({context, next})` | Ajoute à la pile |
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
[← injection.md](injection.md) | [↑ core/](README.md) | [config.md →](config.md)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Système de Routage
|
|
2
|
+
|
|
3
|
+
**Fichiers :** `source/core/router/`
|
|
4
|
+
**Import :** `import { Router, Route, RouteMatcher, createHandler } from "raiton/core"`
|
|
5
|
+
|
|
6
|
+
> **Navigation :** [← application.md](application.md) | [↑ core/](README.md) | [middleware.md →](middleware.md)
|
|
7
|
+
|
|
8
|
+
## `Router`
|
|
9
|
+
|
|
10
|
+
Enregistre et recherche des routes. Utilisé en interne par `PluginScope`.
|
|
11
|
+
|
|
12
|
+
```typescript
|
|
13
|
+
const router = new Router()
|
|
14
|
+
|
|
15
|
+
// Ajouter une route
|
|
16
|
+
const route = router.add("GET", "/users/:id", handler, "v1")
|
|
17
|
+
|
|
18
|
+
// Rechercher une route
|
|
19
|
+
const match = router.match("GET", "/users/42")
|
|
20
|
+
// → { route, parameters: { id: "42" } } ou null
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Méthodes
|
|
24
|
+
|
|
25
|
+
| Méthode | Description |
|
|
26
|
+
|---------|-------------|
|
|
27
|
+
| `add(method, path, handler, version?)` | Ajoute et retourne une `Route` |
|
|
28
|
+
| `match(method, path)` | Cherche une route, retourne `{ route, parameters }` ou `null` |
|
|
29
|
+
| `getRoutes()` | Retourne toutes les routes enregistrées (utilisé par OpenAPI) |
|
|
30
|
+
|
|
31
|
+
## `Route`
|
|
32
|
+
|
|
33
|
+
Représente une route individuelle.
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
class Route {
|
|
37
|
+
method: HttpMethod
|
|
38
|
+
path: string
|
|
39
|
+
handler: Function
|
|
40
|
+
version?: string
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## `RouteMatcher`
|
|
45
|
+
|
|
46
|
+
Moteur de matching avec support des paramètres d'URL.
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
const matcher = new RouteMatcher()
|
|
50
|
+
|
|
51
|
+
matcher.add(route1)
|
|
52
|
+
const result = matcher.lookup("GET", "/users/42")
|
|
53
|
+
// result === { route: Route, parameters: { "0": "42" } } | null
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**Règles de matching :**
|
|
57
|
+
|
|
58
|
+
- Segments statiques : `/users/list` → match exact
|
|
59
|
+
- Paramètres nommés : `/users/:id` → capture `{ "0": "42" }`
|
|
60
|
+
- La priorité va aux routes statiques puis aux routes avec paramètres
|
|
61
|
+
- Les paramètres sont indexés par position (`"0"`, `"1"`, ...) et mappés au handler via `handler.utils.ts`
|
|
62
|
+
|
|
63
|
+
## `createHandler`
|
|
64
|
+
|
|
65
|
+
Wrapper qui prépare un handler de contrôleur pour l'exécution :
|
|
66
|
+
|
|
67
|
+
```typescript
|
|
68
|
+
const wrappedHandler = createHandler(instance, routeMeta, controllerMeta)
|
|
69
|
+
// Le handler résultant :
|
|
70
|
+
// 1. Collecte les arguments depuis le contexte (req, reply, params, body...)
|
|
71
|
+
// 2. Valide les DTO si présents
|
|
72
|
+
// 3. Appelle la méthode du contrôleur
|
|
73
|
+
// 4. Valide la réponse (ViewModel)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Collecte des arguments (`handler.utils.ts`)
|
|
77
|
+
|
|
78
|
+
Le système lit les métadonnées `@Param`, `@Query`, `@Body`, etc. pour injecter automatiquement les bons paramètres dans la méthode du contrôleur.
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
// Exemple de ce que createHandler produit en interne :
|
|
82
|
+
async function handler(context: any) {
|
|
83
|
+
const args = collectArguments(routeMeta, context)
|
|
84
|
+
// args = [42, "Jean"] si la méthode a @Param("id") et @Query("name")
|
|
85
|
+
return await instance[routeMeta.propertyKey](...args)
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Exemple de routage manuel
|
|
90
|
+
|
|
91
|
+
```typescript
|
|
92
|
+
import { Application, Router, RouteMatcher } from "raiton/core"
|
|
93
|
+
import { HttpMethod } from "raiton/framework"
|
|
94
|
+
|
|
95
|
+
const app = new Application({ port: 3000 })
|
|
96
|
+
|
|
97
|
+
// Via l'application
|
|
98
|
+
app.route(HttpMethod.GET, "/items/:id", async (ctx) => {
|
|
99
|
+
const id = ctx.params?.id || ctx.req.param("id")
|
|
100
|
+
return { id, name: "Item " + id }
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
// Via le router directement (usage avancé)
|
|
104
|
+
const router = new Router()
|
|
105
|
+
const route = router.add("GET", "/custom", handler)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Matching avec préfixe et pathname
|
|
109
|
+
|
|
110
|
+
L'`Application.handle()` applique ces transformations avant le matching :
|
|
111
|
+
|
|
112
|
+
1. Si `config.pathname` est défini (ex: `/app`), il est retiré du début du path.
|
|
113
|
+
2. Si `config.prefix` est défini (ex: `/api`), il est ajouté automatiquement dans `Application.route()`.
|
|
114
|
+
|
|
115
|
+
```typescript
|
|
116
|
+
new Application({ prefix: "/api", pathname: "/app" })
|
|
117
|
+
// GET /app/api/users/42 → pathname résolu: /users/42 → route /users/:id
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
[← application.md](application.md) | [↑ core/](README.md) | [middleware.md →](middleware.md)
|