@ddd-ts-kit/http 0.90.0 → 0.92.0
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/README.fr.md +231 -2
- package/README.md +225 -1
- package/dist/controller/controller-request.d.ts +10 -1
- package/dist/controller/controller-request.d.ts.map +1 -1
- package/dist/controller/controller-response.d.ts +6 -0
- package/dist/controller/controller-response.d.ts.map +1 -1
- package/dist/controller/controller-result.d.ts +22 -4
- package/dist/controller/controller-result.d.ts.map +1 -1
- package/dist/controller/controller-routes.d.ts.map +1 -1
- package/dist/controller/controller-routes.js +29 -4
- package/dist/controller/controller-routes.js.map +1 -1
- package/dist/controller/controller-spec.d.ts +7 -0
- package/dist/controller/controller-spec.d.ts.map +1 -1
- package/dist/controller/declared-route.d.ts.map +1 -1
- package/dist/controller/declared-route.js +10 -0
- package/dist/controller/declared-route.js.map +1 -1
- package/dist/controller/http-controller.d.ts +4 -5
- package/dist/controller/http-controller.d.ts.map +1 -1
- package/dist/controller/http-request.d.ts +10 -1
- package/dist/controller/http-request.d.ts.map +1 -1
- package/dist/error/refusal-codes-by-status.d.ts +11 -0
- package/dist/error/refusal-codes-by-status.d.ts.map +1 -0
- package/dist/error/refusal-codes-by-status.js +48 -0
- package/dist/error/refusal-codes-by-status.js.map +1 -0
- package/dist/express/mount-express.d.ts +2 -1
- package/dist/express/mount-express.d.ts.map +1 -1
- package/dist/express/mount-express.js +12 -2
- package/dist/express/mount-express.js.map +1 -1
- package/dist/nest/controllers/arguments-of.d.ts +7 -0
- package/dist/nest/controllers/arguments-of.d.ts.map +1 -0
- package/dist/nest/controllers/arguments-of.js +26 -0
- package/dist/nest/controllers/arguments-of.js.map +1 -0
- package/dist/nest/controllers/assert-not-routed-by-nest.d.ts +8 -0
- package/dist/nest/controllers/assert-not-routed-by-nest.d.ts.map +1 -0
- package/dist/nest/controllers/assert-not-routed-by-nest.js +19 -0
- package/dist/nest/controllers/assert-not-routed-by-nest.js.map +1 -0
- package/dist/nest/controllers/controllers-binder.d.ts +6 -0
- package/dist/nest/controllers/controllers-binder.d.ts.map +1 -0
- package/dist/nest/controllers/controllers-binder.js +5 -0
- package/dist/nest/controllers/controllers-binder.js.map +1 -0
- package/dist/nest/controllers/controllers-module-options.d.ts +8 -0
- package/dist/nest/controllers/controllers-module-options.d.ts.map +1 -0
- package/dist/nest/controllers/controllers-module-options.js +2 -0
- package/dist/nest/controllers/controllers-module-options.js.map +1 -0
- package/dist/nest/controllers/create-controllers-module.d.ts +10 -0
- package/dist/nest/controllers/create-controllers-module.d.ts.map +1 -0
- package/dist/nest/controllers/create-controllers-module.js +28 -0
- package/dist/nest/controllers/create-controllers-module.js.map +1 -0
- package/dist/nest/controllers/current-actor.d.ts +6 -0
- package/dist/nest/controllers/current-actor.d.ts.map +1 -0
- package/dist/nest/controllers/current-actor.js +9 -0
- package/dist/nest/controllers/current-actor.js.map +1 -0
- package/dist/nest/controllers/dto-type.d.ts +3 -0
- package/dist/nest/controllers/dto-type.d.ts.map +1 -0
- package/dist/nest/controllers/dto-type.js +2 -0
- package/dist/nest/controllers/dto-type.js.map +1 -0
- package/dist/nest/controllers/injected-parameter.d.ts +4 -0
- package/dist/nest/controllers/injected-parameter.d.ts.map +1 -0
- package/dist/nest/controllers/injected-parameter.js +17 -0
- package/dist/nest/controllers/injected-parameter.js.map +1 -0
- package/dist/nest/controllers/is-nest-controller.d.ts +4 -0
- package/dist/nest/controllers/is-nest-controller.d.ts.map +1 -0
- package/dist/nest/controllers/is-nest-controller.js +7 -0
- package/dist/nest/controllers/is-nest-controller.js.map +1 -0
- package/dist/nest/controllers/keyed-schema.d.ts +8 -0
- package/dist/nest/controllers/keyed-schema.d.ts.map +1 -0
- package/dist/nest/controllers/keyed-schema.js +33 -0
- package/dist/nest/controllers/keyed-schema.js.map +1 -0
- package/dist/nest/controllers/kit-route-spec.d.ts +71 -0
- package/dist/nest/controllers/kit-route-spec.d.ts.map +1 -0
- package/dist/nest/controllers/kit-route-spec.js +2 -0
- package/dist/nest/controllers/kit-route-spec.js.map +1 -0
- package/dist/nest/controllers/kit-route.d.ts +18 -0
- package/dist/nest/controllers/kit-route.d.ts.map +1 -0
- package/dist/nest/controllers/kit-route.js +29 -0
- package/dist/nest/controllers/kit-route.js.map +1 -0
- package/dist/nest/controllers/kit-routes-options.d.ts +15 -0
- package/dist/nest/controllers/kit-routes-options.d.ts.map +1 -0
- package/dist/nest/controllers/kit-routes-options.js +2 -0
- package/dist/nest/controllers/kit-routes-options.js.map +1 -0
- package/dist/nest/controllers/kit-routes.d.ts +5 -0
- package/dist/nest/controllers/kit-routes.d.ts.map +1 -0
- package/dist/nest/controllers/kit-routes.js +8 -0
- package/dist/nest/controllers/kit-routes.js.map +1 -0
- package/dist/nest/controllers/nest-controller-class.d.ts +3 -0
- package/dist/nest/controllers/nest-controller-class.d.ts.map +1 -0
- package/dist/nest/controllers/nest-controller-class.js +2 -0
- package/dist/nest/controllers/nest-controller-class.js.map +1 -0
- package/dist/nest/controllers/nest-controller-route.d.ts +6 -0
- package/dist/nest/controllers/nest-controller-route.d.ts.map +1 -0
- package/dist/nest/controllers/nest-controller-route.js +12 -0
- package/dist/nest/controllers/nest-controller-route.js.map +1 -0
- package/dist/nest/controllers/nest-controller-routes-options.d.ts +14 -0
- package/dist/nest/controllers/nest-controller-routes-options.d.ts.map +1 -0
- package/dist/nest/controllers/nest-controller-routes-options.js +2 -0
- package/dist/nest/controllers/nest-controller-routes-options.js.map +1 -0
- package/dist/nest/controllers/nest-controller-routes.d.ts +12 -0
- package/dist/nest/controllers/nest-controller-routes.d.ts.map +1 -0
- package/dist/nest/controllers/nest-controller-routes.js +159 -0
- package/dist/nest/controllers/nest-controller-routes.js.map +1 -0
- package/dist/nest/controllers/nest-controllers-options.d.ts +7 -0
- package/dist/nest/controllers/nest-controllers-options.d.ts.map +1 -0
- package/dist/nest/controllers/nest-controllers-options.js +2 -0
- package/dist/nest/controllers/nest-controllers-options.js.map +1 -0
- package/dist/nest/controllers/nest-controllers.d.ts +21 -0
- package/dist/nest/controllers/nest-controllers.d.ts.map +1 -0
- package/dist/nest/controllers/nest-controllers.js +31 -0
- package/dist/nest/controllers/nest-controllers.js.map +1 -0
- package/dist/nest/controllers/nest-method.d.ts +20 -0
- package/dist/nest/controllers/nest-method.d.ts.map +1 -0
- package/dist/nest/controllers/nest-method.js +2 -0
- package/dist/nest/controllers/nest-method.js.map +1 -0
- package/dist/nest/controllers/nest-parameter.d.ts +10 -0
- package/dist/nest/controllers/nest-parameter.d.ts.map +1 -0
- package/dist/nest/controllers/nest-parameter.js +2 -0
- package/dist/nest/controllers/nest-parameter.js.map +1 -0
- package/dist/nest/controllers/nest-route-metadata.d.ts +22 -0
- package/dist/nest/controllers/nest-route-metadata.d.ts.map +1 -0
- package/dist/nest/controllers/nest-route-metadata.js +121 -0
- package/dist/nest/controllers/nest-route-metadata.js.map +1 -0
- package/dist/nest/controllers/nest-route-methods.d.ts +4 -0
- package/dist/nest/controllers/nest-route-methods.d.ts.map +1 -0
- package/dist/nest/controllers/nest-route-methods.js +12 -0
- package/dist/nest/controllers/nest-route-methods.js.map +1 -0
- package/dist/nest/controllers/nest-routes-registry.d.ts +17 -0
- package/dist/nest/controllers/nest-routes-registry.d.ts.map +1 -0
- package/dist/nest/controllers/nest-routes-registry.js +23 -0
- package/dist/nest/controllers/nest-routes-registry.js.map +1 -0
- package/dist/nest/controllers/nest-signature.d.ts +15 -0
- package/dist/nest/controllers/nest-signature.d.ts.map +1 -0
- package/dist/nest/controllers/nest-signature.js +2 -0
- package/dist/nest/controllers/nest-signature.js.map +1 -0
- package/dist/nest/controllers/prototype-of.d.ts +4 -0
- package/dist/nest/controllers/prototype-of.d.ts.map +1 -0
- package/dist/nest/controllers/prototype-of.js +10 -0
- package/dist/nest/controllers/prototype-of.js.map +1 -0
- package/dist/nest/controllers/provide-controllers.d.ts +12 -0
- package/dist/nest/controllers/provide-controllers.d.ts.map +1 -0
- package/dist/nest/controllers/provide-controllers.js +33 -0
- package/dist/nest/controllers/provide-controllers.js.map +1 -0
- package/dist/nest/controllers/reflected-metadata.d.ts +3 -0
- package/dist/nest/controllers/reflected-metadata.d.ts.map +1 -0
- package/dist/nest/controllers/reflected-metadata.js +11 -0
- package/dist/nest/controllers/reflected-metadata.js.map +1 -0
- package/dist/nest/controllers/request-schemas-of.d.ts +14 -0
- package/dist/nest/controllers/request-schemas-of.d.ts.map +1 -0
- package/dist/nest/controllers/request-schemas-of.js +50 -0
- package/dist/nest/controllers/request-schemas-of.js.map +1 -0
- package/dist/nest/controllers/route-context.d.ts +3 -0
- package/dist/nest/controllers/route-context.d.ts.map +1 -0
- package/dist/nest/controllers/route-context.js +6 -0
- package/dist/nest/controllers/route-context.js.map +1 -0
- package/dist/nest/controllers/schema-of.d.ts +6 -0
- package/dist/nest/controllers/schema-of.d.ts.map +1 -0
- package/dist/nest/controllers/schema-of.js +12 -0
- package/dist/nest/controllers/schema-of.js.map +1 -0
- package/dist/nest/controllers/summary-of.d.ts +3 -0
- package/dist/nest/controllers/summary-of.d.ts.map +1 -0
- package/dist/nest/controllers/summary-of.js +6 -0
- package/dist/nest/controllers/summary-of.js.map +1 -0
- package/dist/nest/controllers/upload.d.ts +6 -0
- package/dist/nest/controllers/upload.d.ts.map +1 -0
- package/dist/nest/controllers/upload.js +9 -0
- package/dist/nest/controllers/upload.js.map +1 -0
- package/dist/nest/controllers/with-signatures.d.ts +10 -0
- package/dist/nest/controllers/with-signatures.d.ts.map +1 -0
- package/dist/nest/controllers/with-signatures.js +12 -0
- package/dist/nest/controllers/with-signatures.js.map +1 -0
- package/dist/nest.d.ts +20 -0
- package/dist/nest.d.ts.map +1 -1
- package/dist/nest.js +12 -0
- package/dist/nest.js.map +1 -1
- package/dist/openapi/request-body.d.ts.map +1 -1
- package/dist/openapi/request-body.js +11 -0
- package/dist/openapi/request-body.js.map +1 -1
- package/dist/openapi/responses.d.ts.map +1 -1
- package/dist/openapi/responses.js +12 -42
- package/dist/openapi/responses.js.map +1 -1
- package/dist/orpc/orpc-protocol.d.ts +7 -0
- package/dist/orpc/orpc-protocol.d.ts.map +1 -0
- package/dist/orpc/orpc-protocol.js +13 -0
- package/dist/orpc/orpc-protocol.js.map +1 -0
- package/dist/orpc/orpc-router.d.ts +22 -0
- package/dist/orpc/orpc-router.d.ts.map +1 -0
- package/dist/orpc/orpc-router.js +43 -0
- package/dist/orpc/orpc-router.js.map +1 -0
- package/dist/orpc.d.ts +4 -0
- package/dist/orpc.d.ts.map +1 -0
- package/dist/orpc.js +2 -0
- package/dist/orpc.js.map +1 -0
- package/dist/pipeline/primed.d.ts +2 -1
- package/dist/pipeline/primed.d.ts.map +1 -1
- package/dist/pipeline/primed.js +14 -11
- package/dist/pipeline/primed.js.map +1 -1
- package/dist/route/response-spec.d.ts +2 -0
- package/dist/route/response-spec.d.ts.map +1 -1
- package/dist/rpc/rpc-answer.d.ts +18 -0
- package/dist/rpc/rpc-answer.d.ts.map +1 -0
- package/dist/rpc/rpc-answer.js +61 -0
- package/dist/rpc/rpc-answer.js.map +1 -0
- package/dist/rpc/rpc-context.d.ts +15 -0
- package/dist/rpc/rpc-context.d.ts.map +1 -0
- package/dist/rpc/rpc-context.js +2 -0
- package/dist/rpc/rpc-context.js.map +1 -0
- package/dist/rpc/rpc-input.d.ts +11 -0
- package/dist/rpc/rpc-input.d.ts.map +1 -0
- package/dist/rpc/rpc-input.js +2 -0
- package/dist/rpc/rpc-input.js.map +1 -0
- package/dist/rpc/rpc-refusal.d.ts +14 -0
- package/dist/rpc/rpc-refusal.d.ts.map +1 -0
- package/dist/rpc/rpc-refusal.js +2 -0
- package/dist/rpc/rpc-refusal.js.map +1 -0
- package/dist/rpc/rpc-request.d.ts +9 -0
- package/dist/rpc/rpc-request.d.ts.map +1 -0
- package/dist/rpc/rpc-request.js +28 -0
- package/dist/rpc/rpc-request.js.map +1 -0
- package/dist/trpc/route-refusal.d.ts +8 -0
- package/dist/trpc/route-refusal.d.ts.map +1 -0
- package/dist/trpc/route-refusal.js +10 -0
- package/dist/trpc/route-refusal.js.map +1 -0
- package/dist/trpc/trpc-error-shape.d.ts +17 -0
- package/dist/trpc/trpc-error-shape.d.ts.map +1 -0
- package/dist/trpc/trpc-error-shape.js +2 -0
- package/dist/trpc/trpc-error-shape.js.map +1 -0
- package/dist/trpc/trpc-protocol.d.ts +8 -0
- package/dist/trpc/trpc-protocol.d.ts.map +1 -0
- package/dist/trpc/trpc-protocol.js +43 -0
- package/dist/trpc/trpc-protocol.js.map +1 -0
- package/dist/trpc/trpc-router.d.ts +38 -0
- package/dist/trpc/trpc-router.d.ts.map +1 -0
- package/dist/trpc/trpc-router.js +44 -0
- package/dist/trpc/trpc-router.js.map +1 -0
- package/dist/trpc.d.ts +5 -0
- package/dist/trpc.d.ts.map +1 -0
- package/dist/trpc.js +2 -0
- package/dist/trpc.js.map +1 -0
- package/package.json +30 -7
package/README.fr.md
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
[English](README.md) · **Français**
|
|
2
|
-
<!-- translation-of: README.md sha256:
|
|
2
|
+
<!-- translation-of: README.md sha256:6f250d2a07b22cea -->
|
|
3
3
|
|
|
4
4
|
# @ddd-ts-kit/http
|
|
5
5
|
|
|
6
6
|
Déclarez une route une seule fois, sans framework. Montez-la sur Express 5, Fastify 5, Hono 4
|
|
7
|
-
(sur Node) ou NestJS, et générez le contrat OpenAPI 3.1 à
|
|
7
|
+
(sur Node) ou NestJS, servez-la aussi comme procédure oRPC ou tRPC, et générez le contrat OpenAPI 3.1 à
|
|
8
|
+
partir de la même déclaration.
|
|
8
9
|
|
|
9
10
|
Chaque adaptateur passe par un seul pipeline (`executeRoute`) : validation, gestionnaire
|
|
10
11
|
(handler), correspondance des erreurs. Le comportement est donc le même sur les quatre
|
|
@@ -1300,6 +1301,229 @@ contournent les pipes, les guards, les intercepteurs, les filtres d'exceptions e
|
|
|
1300
1301
|
global de Nest : la validation et la correspondance des erreurs sont celles décrites plus haut.
|
|
1301
1302
|
Utilisez `prefixRoutes` pour un préfixe.
|
|
1302
1303
|
|
|
1304
|
+
### Contrôleurs Nest servis par le kit
|
|
1305
|
+
|
|
1306
|
+
Un projet qui écrit des contrôleurs Nest les garde : `@Controller`, `@Get`, `@Post` et les autres
|
|
1307
|
+
méthodes, `@Param`, `@Query`, `@Headers`, `@Body` avec une classe DTO, `@HttpCode`, l'injection par
|
|
1308
|
+
constructeur et les modules. Chaque méthode qui porte un décorateur de route de Nest est une route
|
|
1309
|
+
du kit, nommée d'après la méthode (`issueInvoice`, résumé `Issue invoice` ; renommer la méthode
|
|
1310
|
+
renomme la route, sa procédure et la fonction de son client), derrière les *guards* de `@KitRoutes`
|
|
1311
|
+
sur la classe. `@KitRoute` sur une méthode, facultatif, ajoute ce que Nest ne dit pas :
|
|
1312
|
+
un autre nom, ses propres *guards*, les refus qu'elle répond, sa réponse. C'est le kit, et non le
|
|
1313
|
+
routeur de Nest, qui sert la méthode : c'est une route du kit, avec ses *guards*, sa validation, ses
|
|
1314
|
+
documents *problem*, son traçage et son contrat, et une procédure sur `/rpc` et `/trpc` comme toute
|
|
1315
|
+
route.
|
|
1316
|
+
|
|
1317
|
+
<!-- checked sample: legacy-decorators -->
|
|
1318
|
+
```ts
|
|
1319
|
+
import { Body, Controller, Inject, Module, Param, Post } from '@nestjs/common';
|
|
1320
|
+
import { IsString, MinLength } from 'class-validator';
|
|
1321
|
+
import type { Actor } from '@ddd-ts-kit/kernel';
|
|
1322
|
+
import { Authenticated, type ExecuteOptions } from '@ddd-ts-kit/http';
|
|
1323
|
+
import { createControllersModule, CurrentActor, KitRoute, KitRoutes } from '@ddd-ts-kit/http/nest';
|
|
1324
|
+
import { classSchema } from '@ddd-ts-kit/validation/class-validator';
|
|
1325
|
+
|
|
1326
|
+
declare const options: ExecuteOptions;
|
|
1327
|
+
|
|
1328
|
+
/** What the controller sends its use case through: here a port of the application. */
|
|
1329
|
+
abstract class Invoicing {
|
|
1330
|
+
abstract issue(invoiceId: string, customerId: string, actor: Actor): Promise<void>;
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
declare const invoicing: Invoicing;
|
|
1334
|
+
|
|
1335
|
+
class IssueInvoiceBody {
|
|
1336
|
+
@IsString()
|
|
1337
|
+
@MinLength(1)
|
|
1338
|
+
customerId = '';
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
@Controller('invoices')
|
|
1342
|
+
@KitRoutes({ guards: [Authenticated], tags: ['Invoices'] })
|
|
1343
|
+
export class InvoicesController {
|
|
1344
|
+
constructor(@Inject(Invoicing) private readonly invoicing: Invoicing) {}
|
|
1345
|
+
|
|
1346
|
+
@Post(':invoiceId/issue')
|
|
1347
|
+
@KitRoute({ errors: ['INVOICE_ALREADY_ISSUED'] }) // named issueInvoice, after the method
|
|
1348
|
+
async issue(
|
|
1349
|
+
@Param('invoiceId') invoiceId: string,
|
|
1350
|
+
@Body() body: IssueInvoiceBody,
|
|
1351
|
+
@CurrentActor() actor: Actor,
|
|
1352
|
+
): Promise<void> {
|
|
1353
|
+
await this.invoicing.issue(invoiceId, body.customerId, actor);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
@Module({
|
|
1358
|
+
imports: [
|
|
1359
|
+
createControllersModule([InvoicesController], {
|
|
1360
|
+
...options,
|
|
1361
|
+
providers: [{ provide: Invoicing, useValue: invoicing }],
|
|
1362
|
+
schemaOfClass: classSchema,
|
|
1363
|
+
}),
|
|
1364
|
+
],
|
|
1365
|
+
})
|
|
1366
|
+
export class AppModule {}
|
|
1367
|
+
```
|
|
1368
|
+
|
|
1369
|
+
- `createControllersModule(controllers, options)` enregistre les contrôleurs comme *providers*,
|
|
1370
|
+
pour que Nest les construise avec ce qu'ils injectent, et monte chaque méthode portant
|
|
1371
|
+
`@KitRoute` sur le serveur HTTP sous Nest. Un contrôleur listé aussi dans les `controllers` d'un
|
|
1372
|
+
module Nest est refusé au démarrage : Nest le servirait une seconde fois, par son propre pipeline.
|
|
1373
|
+
- `@KitRoutes({ guards, tags, errors })` sur la classe est ce que toutes ses routes partagent, comme
|
|
1374
|
+
un groupe de routes ; les `guards` de `@KitRoute` passent après. Une route sans *guard* ni d'un
|
|
1375
|
+
côté ni de l'autre est refusée : `[Public]` dit qu'elle est ouverte.
|
|
1376
|
+
- `@CurrentActor()` donne à la méthode l'appelant que l'authentification a résolu
|
|
1377
|
+
(`resolvePrincipal`), jamais un appelant construit par le contrôleur ; `@RouteContext()` le
|
|
1378
|
+
contexte de la requête (`expectedVersion` sous `ifMatch`) ; `@Upload()` le fichier que déclare
|
|
1379
|
+
`upload` de `@KitRoute`, lu en flux et vérifié par le kit contre sa taille et ses types de média,
|
|
1380
|
+
jamais analysé par Nest (une méthode qui le prend sans `upload` déclaré est refusée à la
|
|
1381
|
+
construction des routes).
|
|
1382
|
+
- `@KitRoute` porte aussi ce qu'un contrôleur du kit déclare en plus de sa route : `upload`,
|
|
1383
|
+
`form` (`defineForm(...)`, servi à `GET /forms/<operationId>`), `produces` et `consumes`,
|
|
1384
|
+
`cache`, `ifMatch`.
|
|
1385
|
+
- Un paramètre qui prend une partie entière est validé par sa classe, lue par `schemaOfClass`
|
|
1386
|
+
(`classSchema` de class-validator) : la classe que nomme `withSignatures`, sinon celle que
|
|
1387
|
+
TypeScript a enregistrée sous `emitDecoratorMetadata`, que tsx et esbuild n'écrivent pas ; une partie nommée une à une (`@Param('invoiceId')`) est un texte ; `request` de
|
|
1388
|
+
`@KitRoute` donne à la place un schéma de n'importe quelle bibliothèque. `response.body` est un
|
|
1389
|
+
schéma ou une classe DTO. Une méthode ne répond un corps que si `response.body` le déclare, comme
|
|
1390
|
+
le dit le contrat : une méthode qui rend une valeur sans lui est refusée, à la construction des
|
|
1391
|
+
routes si TypeScript a enregistré son type de retour, sinon à l'appel (une 500, signalée à
|
|
1392
|
+
`onError`), jamais répondue vide.
|
|
1393
|
+
- `nestControllerRoutes(controllers, { schemaOfClass })` donne les mêmes routes sans le conteneur
|
|
1394
|
+
de Nest, pour `generateOpenApi`, `orpcRouter` et `trpcRouter` ; `nestControllerRoute` l'unique
|
|
1395
|
+
route d'un contrôleur, pour sa spec.
|
|
1396
|
+
- Une application qui compose ses routes avant le démarrage de Nest prend
|
|
1397
|
+
`nestControllers(controllers, { providers, schemaOfClass })` : ses `routes` rejoignent les autres
|
|
1398
|
+
routes de l'application, et `provideControllers(served)` dans le module Nest construit les
|
|
1399
|
+
contrôleurs avec ce qu'ils injectent (les bus, comme `{ provide: CommandBus, useValue: commands }`)
|
|
1400
|
+
et donne aux routes leurs instances au démarrage. `ddd-ts-kit init --http nest` écrit cette
|
|
1401
|
+
composition (`--routes nest`, la valeur par défaut d'un projet Nest sur class-validator).
|
|
1402
|
+
- `@KitRoutes({ group })` nomme un groupe de routes du kit (`@RouteGroup`) : son préfixe précède les
|
|
1403
|
+
chemins de Nest, ses tags, *guards* et codes précèdent ceux de la classe.
|
|
1404
|
+
- Ce qu'une méthode prend et répond, c'est sa signature : TypeScript efface `Promise<IssuedInvoice>`,
|
|
1405
|
+
et n'enregistre les classes des paramètres que sous `emitDecoratorMetadata`, donc
|
|
1406
|
+
`withSignatures(controller, { issueInvoice: { body: IssueInvoiceBody, answer: IssuedInvoice } })`
|
|
1407
|
+
le dit au pont : la classe DTO de chaque partie qu'un paramètre prend entière (`params`, `query`,
|
|
1408
|
+
`headers`, `body`), et la réponse, une classe DTO, un schéma ou `null` pour aucun corps ;
|
|
1409
|
+
`request` et `response` de `@KitRoute` l'emportent toujours. Sous `--routes nest`, `ddd-ts-kit`
|
|
1410
|
+
lit les signatures et écrit ces appels dans le fichier généré `<context>.controllers.ts`, que le
|
|
1411
|
+
module du contexte liste.
|
|
1412
|
+
- Refusés quand les routes sont construites, parce que le pipeline du kit ne les exécuterait pas :
|
|
1413
|
+
`@UseGuards`, `@UsePipes`, `@UseInterceptors`, `@UseFilters`, `@Header`, `@Redirect`, `@Render`,
|
|
1414
|
+
`@Sse`, `@Version`, un *pipe* sur un paramètre, `@Req`, `@Res` et les autres paramètres de Nest. Le
|
|
1415
|
+
kit lit ce qu'enregistrent les décorateurs de Nest (`@nestjs/common/constants`) ; la forme en est
|
|
1416
|
+
vérifiée à chaque lecture, et un test du kit la tient sur la version de Nest avec laquelle il est
|
|
1417
|
+
publié : une version de Nest qui la changerait est refusée au démarrage plutôt que lue de travers.
|
|
1418
|
+
|
|
1419
|
+
## Procédures oRPC
|
|
1420
|
+
|
|
1421
|
+
Une seconde porte vers les mêmes routes, pour un client TypeScript qui appelle des procédures
|
|
1422
|
+
plutôt que des chemins. `orpcRouter` fait de chaque route une procédure oRPC nommée par son
|
|
1423
|
+
`operationId`, que `RPCHandler` de `@orpc/server` (1.15 ou plus récent, pair optionnelle) sert
|
|
1424
|
+
sous un préfixe, à côté des routes elles-mêmes. Chaque appel passe par `executeRoute` avec les
|
|
1425
|
+
options données à l'adaptateur HTTP : les gardes, le principal, le tenant, la validation, les
|
|
1426
|
+
permissions du cas d'usage, `onError` et `around` voient un appel sur `/rpc` comme ils voient une
|
|
1427
|
+
requête.
|
|
1428
|
+
|
|
1429
|
+
<!-- checked sample -->
|
|
1430
|
+
```ts
|
|
1431
|
+
import express from 'express';
|
|
1432
|
+
import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
|
|
1433
|
+
import { mountExpress } from '@ddd-ts-kit/http/express';
|
|
1434
|
+
import { orpcRouter } from '@ddd-ts-kit/http/orpc';
|
|
1435
|
+
import { RPCHandler } from '@orpc/server/node';
|
|
1436
|
+
|
|
1437
|
+
declare const routes: readonly Route[];
|
|
1438
|
+
declare const options: ExecuteOptions;
|
|
1439
|
+
|
|
1440
|
+
const app = express();
|
|
1441
|
+
const rpc = new RPCHandler(orpcRouter(routes, options));
|
|
1442
|
+
|
|
1443
|
+
app.use(express.json()); // oRPC lit le corps qu'Express a déjà analysé
|
|
1444
|
+
app.use('/rpc', (request, response, next) => {
|
|
1445
|
+
const context = { headers: request.headers, raw: request };
|
|
1446
|
+
|
|
1447
|
+
void rpc.handle(request, response, { prefix: '/rpc', context }).then(({ matched }) => {
|
|
1448
|
+
if (!matched) {
|
|
1449
|
+
next();
|
|
1450
|
+
}
|
|
1451
|
+
}, next);
|
|
1452
|
+
});
|
|
1453
|
+
mountExpress(app, routes, options);
|
|
1454
|
+
```
|
|
1455
|
+
|
|
1456
|
+
Le `context` d'un appel est un `OrpcContext` : les en-têtes de la requête RPC, qui portent les
|
|
1457
|
+
identifiants, les identifiants de requête et de corrélation et le tenant, et `raw`, ce que lit
|
|
1458
|
+
`resolvePrincipal` (`{ headers }` quand il est omis, ce que lit `principalResolver` de
|
|
1459
|
+
`@ddd-ts-kit/auth`). Fastify (`@orpc/server/fastify`), Hono (`@orpc/server/fetch`) et NestJS sur
|
|
1460
|
+
Express (`@orpc/server/node`) le montent de la même façon ; `ddd-ts-kit init --rpc orpc` écrit le
|
|
1461
|
+
montage pour le framework du projet, et `ddd-ts-kit sdk` donne à chaque client le contrat oRPC de
|
|
1462
|
+
son document, sous `<client>/orpc`.
|
|
1463
|
+
|
|
1464
|
+
| | Sur `/rpc` |
|
|
1465
|
+
|---|---|
|
|
1466
|
+
| Entrée | `{ path, query, header, body }`, l'entrée de l'opération dans le client généré ; `header` passe par-dessus les en-têtes de la requête RPC |
|
|
1467
|
+
| Réponse | le corps du succès, tel que JSON l'écrit (une date est son texte, comme le dit le contrat) ; un corps binaire est un `Blob` |
|
|
1468
|
+
| Refus | une `ORPCError` : le `code` et le `status` du *problem*, son `detail` (ou son `title`) comme `message`, le document *problem* comme `data`. C'est une erreur définie quand la route déclare son code (ses codes et ceux de ses gardes, `VALIDATION_FAILED`, les préconditions), avec le statut que lui donne le correspondant d'erreurs de l'application. Un refus que le gestionnaire répond lui-même, sans document *problem*, est `HTTP_<statut>` avec son corps comme `data` |
|
|
1469
|
+
| `If-Match` | envoyé dans `header`, vérifié comme sur la route |
|
|
1470
|
+
| En-têtes de la réponse | non rendus : ni `ETag`, ni politique de cache, ni `Location`. Un cache partagé ne garde rien de `/rpc` et n'a rien à purger |
|
|
1471
|
+
| Représentations | aucune : JSON seulement, donc ni 406 ni 415 pour un type de média |
|
|
1472
|
+
| Téléversement, corps brut | pas une procédure : seule la route HTTP reçoit un fichier |
|
|
1473
|
+
| Fichier, liste lue au fil de l'eau | refusés en 406 (`NOT_ACCEPTABLE`, son *problem* comme `data`) et fermés, sans rien lire de plus : ils sont envoyés en flux parce qu'ils peuvent ne pas tenir en mémoire |
|
|
1474
|
+
|
|
1475
|
+
Deux routes d'un même `operationId` sont refusées, comme `mountExpress` les refuse : une
|
|
1476
|
+
procédure cacherait l'autre.
|
|
1477
|
+
|
|
1478
|
+
## Procédures tRPC
|
|
1479
|
+
|
|
1480
|
+
La même porte pour un client tRPC. `trpcRouter` fait de chaque route une procédure tRPC nommée
|
|
1481
|
+
par son `operationId`, une *query* pour une route `GET` et une *mutation* pour les autres
|
|
1482
|
+
méthodes, que les adaptateurs de `@trpc/server` (11.10 ou plus récent, pair optionnelle) servent
|
|
1483
|
+
sous un point d'entrée comme `/trpc`. Chaque appel passe par `executeRoute` avec les options de
|
|
1484
|
+
l'adaptateur HTTP, comme un appel d'`orpcRouter`.
|
|
1485
|
+
|
|
1486
|
+
<!-- checked sample -->
|
|
1487
|
+
```ts
|
|
1488
|
+
import express from 'express';
|
|
1489
|
+
import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
|
|
1490
|
+
import { mountExpress } from '@ddd-ts-kit/http/express';
|
|
1491
|
+
import { trpcRouter } from '@ddd-ts-kit/http/trpc';
|
|
1492
|
+
import { createExpressMiddleware } from '@trpc/server/adapters/express';
|
|
1493
|
+
|
|
1494
|
+
declare const routes: readonly Route[];
|
|
1495
|
+
declare const options: ExecuteOptions;
|
|
1496
|
+
|
|
1497
|
+
const app = express();
|
|
1498
|
+
|
|
1499
|
+
app.use(express.json()); // tRPC lit le corps qu'Express a déjà analysé
|
|
1500
|
+
app.use(
|
|
1501
|
+
'/trpc',
|
|
1502
|
+
createExpressMiddleware({
|
|
1503
|
+
router: trpcRouter(routes, options),
|
|
1504
|
+
createContext: ({ req }) => ({ headers: req.headers, raw: req }),
|
|
1505
|
+
}),
|
|
1506
|
+
);
|
|
1507
|
+
mountExpress(app, routes, options);
|
|
1508
|
+
```
|
|
1509
|
+
|
|
1510
|
+
Le contexte d'un appel est un `TrpcContext`, le même qu'`OrpcContext`. Fastify
|
|
1511
|
+
(`@trpc/server/adapters/fastify`), Hono (`@trpc/server/adapters/fetch`) et NestJS sur Express
|
|
1512
|
+
(`@trpc/server/adapters/standalone`) le montent de la même façon ; `ddd-ts-kit init --rpc trpc`
|
|
1513
|
+
écrit le montage pour le framework du projet, et `ddd-ts-kit sdk` donne à chaque client le type du
|
|
1514
|
+
routeur, sous `<client>/trpc`. Montez-le comme un routeur à part, sans le fusionner dans un autre :
|
|
1515
|
+
tRPC met en forme une erreur avec le formateur du routeur qu'il sert, et c'est celui de
|
|
1516
|
+
`trpcRouter` qui place le document *problem* dans `data.problem`.
|
|
1517
|
+
|
|
1518
|
+
| | Sur `/trpc` |
|
|
1519
|
+
|---|---|
|
|
1520
|
+
| Procédure | une *query* pour une route `GET` (`client.getOrder.query(input)`), une *mutation* pour les autres méthodes (`client.placeOrder.mutate(input)`) |
|
|
1521
|
+
| Entrée | `{ path, query, header, body }`, comme sur `/rpc` |
|
|
1522
|
+
| Réponse | le corps du succès, tel que JSON l'écrit |
|
|
1523
|
+
| Refus | une `TRPCError` du code que tRPC a pour le statut (`UNAUTHORIZED` pour 401, `NOT_FOUND` pour 404, `CONFLICT` pour 409, `UNPROCESSABLE_CONTENT` pour 422 ; `BAD_REQUEST` ou `INTERNAL_SERVER_ERROR` pour un statut sans code), le `detail` (ou le `title`) du *problem* comme `message`, et le document *problem* comme `data.problem`. tRPC a une liste fixe de codes : c'est le `code` du *problem*, celui du kit, qui permet à un client de distinguer les refus. `data.problem` vaut `null` pour un refus que le gestionnaire répond lui-même, sans document *problem* (son message est `HTTP_<statut>`), et pour une erreur de tRPC lui-même, comme une procédure inconnue. La pile d'appels que tRPC ajoute en développement est retirée |
|
|
1524
|
+
| `If-Match`, en-têtes de la réponse, représentations, téléversements et corps bruts | comme sur `/rpc` |
|
|
1525
|
+
| Fichier, liste lue au fil de l'eau, corps binaire | refusés en 406 (`NOT_ACCEPTABLE` dans `data.problem`) et fermés : tRPC ne répond qu'en JSON |
|
|
1526
|
+
|
|
1303
1527
|
## OpenAPI 3.1
|
|
1304
1528
|
|
|
1305
1529
|
<!-- checked sample -->
|
|
@@ -1565,6 +1789,11 @@ schéma de corps n'est jamais refusée par un 406.
|
|
|
1565
1789
|
est coupée, le client voit un corps tronqué, et `onError` est prévenu. Les éléments d'un flux
|
|
1566
1790
|
ne sont pas vérifiés un par un par `validateResponses`.
|
|
1567
1791
|
- CSV est écrit, jamais lu, et ne contient que des lignes plates.
|
|
1792
|
+
- Une procédure oRPC ou tRPC ne répond que son corps : ce qu'une route dit dans ses en-têtes (un
|
|
1793
|
+
`ETag`, une politique de cache, un `Location`) reste à la route HTTP, comme les téléversements,
|
|
1794
|
+
les corps bruts, les fichiers, les listes lues au fil de l'eau et les représentations autres que
|
|
1795
|
+
JSON (voir « Procédures oRPC ») ; sur tRPC, les corps binaires aussi, et un refus porte le code
|
|
1796
|
+
que tRPC a pour son statut, celui du kit étant dans `data.problem`.
|
|
1568
1797
|
- Un formulaire décrit des scalaires, des objets imbriqués et des listes d'un vocabulaire fermé ;
|
|
1569
1798
|
une liste d'objets est un champ `list` sans détail. La mise en page au-delà des groupes et de
|
|
1570
1799
|
l'ordre revient au front-end. Une consultation nomme la route des options ; la façon dont le
|
package/README.md
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
# @ddd-ts-kit/http
|
|
4
4
|
|
|
5
5
|
Declare a route once, without a framework. Mount it on Express 5, Fastify 5, Hono 4 (on Node)
|
|
6
|
-
or NestJS, and generate the OpenAPI 3.1 contract from the
|
|
6
|
+
or NestJS, serve it as an oRPC or tRPC procedure too, and generate the OpenAPI 3.1 contract from the
|
|
7
|
+
same declaration.
|
|
7
8
|
|
|
8
9
|
Every adapter goes through one pipeline (`executeRoute`): validation, handler, error mapping.
|
|
9
10
|
The behaviour is therefore the same on the four frameworks, and one test suite proves it.
|
|
@@ -1247,6 +1248,224 @@ A plain array works as well: `createRoutesModule(routes, options)`. These routes
|
|
|
1247
1248
|
pipes, guards, interceptors, exception filters and global prefix: validation and error mapping
|
|
1248
1249
|
are those described above. Use `prefixRoutes` for a prefix.
|
|
1249
1250
|
|
|
1251
|
+
### Nest controllers served by the kit
|
|
1252
|
+
|
|
1253
|
+
A project that writes Nest controllers keeps them: `@Controller`, `@Get`, `@Post` and the other
|
|
1254
|
+
methods, `@Param`, `@Query`, `@Headers`, `@Body` with a DTO class, `@HttpCode`, injection by
|
|
1255
|
+
constructor and modules. Each method that carries a route decorator of Nest is a route of the
|
|
1256
|
+
kit, named after the method (`issueInvoice`, summary `Issue invoice`; renaming the method renames
|
|
1257
|
+
the route, its procedure and the function of its client), behind the guards of `@KitRoutes` on
|
|
1258
|
+
the class. `@KitRoute` on a method, optional, adds what Nest does not say: another
|
|
1259
|
+
name, its own guards, the refusals it answers, its answer. The kit, not Nest's router,
|
|
1260
|
+
serves the method: it is a route of the kit, with its guards, validation, problem documents,
|
|
1261
|
+
tracing and contract, and a procedure over `/rpc` and `/trpc` as every route.
|
|
1262
|
+
|
|
1263
|
+
<!-- checked sample: legacy-decorators -->
|
|
1264
|
+
```ts
|
|
1265
|
+
import { Body, Controller, Inject, Module, Param, Post } from '@nestjs/common';
|
|
1266
|
+
import { IsString, MinLength } from 'class-validator';
|
|
1267
|
+
import type { Actor } from '@ddd-ts-kit/kernel';
|
|
1268
|
+
import { Authenticated, type ExecuteOptions } from '@ddd-ts-kit/http';
|
|
1269
|
+
import { createControllersModule, CurrentActor, KitRoute, KitRoutes } from '@ddd-ts-kit/http/nest';
|
|
1270
|
+
import { classSchema } from '@ddd-ts-kit/validation/class-validator';
|
|
1271
|
+
|
|
1272
|
+
declare const options: ExecuteOptions;
|
|
1273
|
+
|
|
1274
|
+
/** What the controller sends its use case through: here a port of the application. */
|
|
1275
|
+
abstract class Invoicing {
|
|
1276
|
+
abstract issue(invoiceId: string, customerId: string, actor: Actor): Promise<void>;
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
declare const invoicing: Invoicing;
|
|
1280
|
+
|
|
1281
|
+
class IssueInvoiceBody {
|
|
1282
|
+
@IsString()
|
|
1283
|
+
@MinLength(1)
|
|
1284
|
+
customerId = '';
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
@Controller('invoices')
|
|
1288
|
+
@KitRoutes({ guards: [Authenticated], tags: ['Invoices'] })
|
|
1289
|
+
export class InvoicesController {
|
|
1290
|
+
constructor(@Inject(Invoicing) private readonly invoicing: Invoicing) {}
|
|
1291
|
+
|
|
1292
|
+
@Post(':invoiceId/issue')
|
|
1293
|
+
@KitRoute({ errors: ['INVOICE_ALREADY_ISSUED'] }) // named issueInvoice, after the method
|
|
1294
|
+
async issue(
|
|
1295
|
+
@Param('invoiceId') invoiceId: string,
|
|
1296
|
+
@Body() body: IssueInvoiceBody,
|
|
1297
|
+
@CurrentActor() actor: Actor,
|
|
1298
|
+
): Promise<void> {
|
|
1299
|
+
await this.invoicing.issue(invoiceId, body.customerId, actor);
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
@Module({
|
|
1304
|
+
imports: [
|
|
1305
|
+
createControllersModule([InvoicesController], {
|
|
1306
|
+
...options,
|
|
1307
|
+
providers: [{ provide: Invoicing, useValue: invoicing }],
|
|
1308
|
+
schemaOfClass: classSchema,
|
|
1309
|
+
}),
|
|
1310
|
+
],
|
|
1311
|
+
})
|
|
1312
|
+
export class AppModule {}
|
|
1313
|
+
```
|
|
1314
|
+
|
|
1315
|
+
- `createControllersModule(controllers, options)` registers the controllers as providers, so that
|
|
1316
|
+
Nest builds them with what they inject, and mounts each method carrying `@KitRoute` on the
|
|
1317
|
+
HTTP server underneath Nest. A controller also listed in the `controllers` of a Nest module is
|
|
1318
|
+
refused at the start: Nest would serve it a second time, through its own pipeline.
|
|
1319
|
+
- `@KitRoutes({ guards, tags, errors })` on the class is what every route shares, as a route group;
|
|
1320
|
+
`guards` of `@KitRoute` run after. A route with no guard on either is refused: `[Public]` says
|
|
1321
|
+
it is open.
|
|
1322
|
+
- `@CurrentActor()` hands the method the caller the authentication resolved (`resolvePrincipal`),
|
|
1323
|
+
never one the controller builds; `@RouteContext()` the context of the request (`expectedVersion`
|
|
1324
|
+
under `ifMatch`); `@Upload()` the file `upload` of `@KitRoute` declares, streamed and checked by
|
|
1325
|
+
the kit against its size and its media types, never parsed by Nest (a method that takes it with
|
|
1326
|
+
no `upload` declared is refused when the routes are built).
|
|
1327
|
+
- `@KitRoute` also carries what a controller of the kit declares besides its route: `upload`,
|
|
1328
|
+
`form` (`defineForm(...)`, served at `GET /forms/<operationId>`), `produces` and `consumes`,
|
|
1329
|
+
`cache`, `ifMatch`.
|
|
1330
|
+
- A parameter that takes a part whole is validated by its class, read through `schemaOfClass`
|
|
1331
|
+
(`classSchema` of class-validator): the class `withSignatures` names, else the one TypeScript
|
|
1332
|
+
recorded under `emitDecoratorMetadata`, which tsx and esbuild do not write; a part named one by one (`@Param('invoiceId')`) is a text; `request` of `@KitRoute`
|
|
1333
|
+
gives a schema of any library instead. `response.body` is a schema or a DTO class. A method
|
|
1334
|
+
answers a body only when `response.body` declares it, as the contract says: one that returns a
|
|
1335
|
+
value without it is refused, when the routes are built if TypeScript recorded its return type,
|
|
1336
|
+
else at the call (a 500, told to `onError`), never answered empty.
|
|
1337
|
+
- `nestControllerRoutes(controllers, { schemaOfClass })` gives the same routes without Nest's
|
|
1338
|
+
container, for `generateOpenApi`, `orpcRouter` and `trpcRouter`; `nestControllerRoute` the one
|
|
1339
|
+
route of a controller, for its spec.
|
|
1340
|
+
- An application that composes its routes before Nest starts takes `nestControllers(controllers,
|
|
1341
|
+
{ providers, schemaOfClass })`: its `routes` join the other routes of the application, and
|
|
1342
|
+
`provideControllers(served)` in the Nest module builds the controllers with what they inject
|
|
1343
|
+
(the buses, as `{ provide: CommandBus, useValue: commands }`) and hands the routes their
|
|
1344
|
+
instances at the start. `ddd-ts-kit init --http nest` writes that composition (`--routes nest`, the default of a Nest project on class-validator).
|
|
1345
|
+
- `@KitRoutes({ group })` names a route group of the kit (`@RouteGroup`): its prefix comes before
|
|
1346
|
+
the paths of Nest, its tags, guards and codes before those of the class.
|
|
1347
|
+
- What a method takes and answers is its signature: TypeScript erases `Promise<IssuedInvoice>`,
|
|
1348
|
+
and records the classes of the parameters only under `emitDecoratorMetadata`, so
|
|
1349
|
+
`withSignatures(controller, { issueInvoice: { body: IssueInvoiceBody, answer: IssuedInvoice } })`
|
|
1350
|
+
says it to the bridge: the DTO class of each part a parameter takes whole (`params`, `query`,
|
|
1351
|
+
`headers`, `body`), and the answer, a DTO class, a schema or `null` for no body; `request` and
|
|
1352
|
+
`response` of `@KitRoute` still win. Under `--routes nest`, `ddd-ts-kit` reads the signatures
|
|
1353
|
+
and writes these calls in the generated `<context>.controllers.ts`, which the module of the
|
|
1354
|
+
context lists.
|
|
1355
|
+
- Refused when the routes are built, because the kit's pipeline would not run them: `@UseGuards`,
|
|
1356
|
+
`@UsePipes`, `@UseInterceptors`, `@UseFilters`, `@Header`, `@Redirect`, `@Render`, `@Sse`,
|
|
1357
|
+
`@Version`, a pipe on a parameter, `@Req`, `@Res` and the other parameters of Nest. The kit
|
|
1358
|
+
reads what Nest's decorators record (`@nestjs/common/constants`); its shape is checked on every
|
|
1359
|
+
read, and a test of the kit holds it on the Nest it is released with, so a release of Nest that
|
|
1360
|
+
changes it is refused at the start rather than read wrong.
|
|
1361
|
+
|
|
1362
|
+
## oRPC procedures
|
|
1363
|
+
|
|
1364
|
+
A second door to the same routes, for a TypeScript client that calls procedures rather than
|
|
1365
|
+
paths. `orpcRouter` turns each route into an oRPC procedure named by its `operationId`, which
|
|
1366
|
+
`RPCHandler` of `@orpc/server` (1.15 or later, an optional peer) serves under a prefix, next to
|
|
1367
|
+
the routes themselves. Each call runs through `executeRoute` with the options the HTTP adapter
|
|
1368
|
+
is given: the guards, the principal, the tenant, the validation, the permissions of the use case,
|
|
1369
|
+
`onError` and `around` see a call over `/rpc` as they see a request.
|
|
1370
|
+
|
|
1371
|
+
<!-- checked sample -->
|
|
1372
|
+
```ts
|
|
1373
|
+
import express from 'express';
|
|
1374
|
+
import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
|
|
1375
|
+
import { mountExpress } from '@ddd-ts-kit/http/express';
|
|
1376
|
+
import { orpcRouter } from '@ddd-ts-kit/http/orpc';
|
|
1377
|
+
import { RPCHandler } from '@orpc/server/node';
|
|
1378
|
+
|
|
1379
|
+
declare const routes: readonly Route[];
|
|
1380
|
+
declare const options: ExecuteOptions;
|
|
1381
|
+
|
|
1382
|
+
const app = express();
|
|
1383
|
+
const rpc = new RPCHandler(orpcRouter(routes, options));
|
|
1384
|
+
|
|
1385
|
+
app.use(express.json()); // oRPC reads the body Express already parsed
|
|
1386
|
+
app.use('/rpc', (request, response, next) => {
|
|
1387
|
+
const context = { headers: request.headers, raw: request };
|
|
1388
|
+
|
|
1389
|
+
void rpc.handle(request, response, { prefix: '/rpc', context }).then(({ matched }) => {
|
|
1390
|
+
if (!matched) {
|
|
1391
|
+
next();
|
|
1392
|
+
}
|
|
1393
|
+
}, next);
|
|
1394
|
+
});
|
|
1395
|
+
mountExpress(app, routes, options);
|
|
1396
|
+
```
|
|
1397
|
+
|
|
1398
|
+
The `context` of a call is `OrpcContext`: the headers of the RPC request, which carry the
|
|
1399
|
+
credentials, the request and correlation ids and the tenant, and `raw`, what `resolvePrincipal`
|
|
1400
|
+
reads (`{ headers }` when it is left out, which `principalResolver` of `@ddd-ts-kit/auth` reads).
|
|
1401
|
+
Fastify (`@orpc/server/fastify`), Hono (`@orpc/server/fetch`) and NestJS on Express
|
|
1402
|
+
(`@orpc/server/node`) mount it the same way; `ddd-ts-kit init --rpc orpc` writes the mount for
|
|
1403
|
+
the framework of the project, and `ddd-ts-kit sdk` gives each client the oRPC contract of its
|
|
1404
|
+
document, at `<client>/orpc`.
|
|
1405
|
+
|
|
1406
|
+
| | Over `/rpc` |
|
|
1407
|
+
|---|---|
|
|
1408
|
+
| Input | `{ path, query, header, body }`, the input of the operation in the generated client; `header` goes over the headers of the RPC request |
|
|
1409
|
+
| Answer | the body of the success, as JSON writes it (a date is its text, as the contract says); a binary body is a `Blob` |
|
|
1410
|
+
| Refusal | an `ORPCError`: the `code` and `status` of the problem, its `detail` (or `title`) as `message`, the problem document as `data`. It is a defined error when the route declares its code (its own codes and those of its guards, `VALIDATION_FAILED`, the preconditions), with the status the error mapper of the application gives it. A refusal the handler answers itself, without a problem document, is `HTTP_<status>` with its body as `data` |
|
|
1411
|
+
| `If-Match` | sent in `header`, checked as on the route |
|
|
1412
|
+
| Headers of the answer | not returned: no `ETag`, no cache policy, no `Location`. A shared cache keeps nothing of `/rpc` and needs no purge |
|
|
1413
|
+
| Representations | none: JSON only, so no 406 nor 415 for a media type |
|
|
1414
|
+
| Upload, raw body | not a procedure: only the HTTP route receives a file |
|
|
1415
|
+
| File, list streamed as it is read | refused with 406 (`NOT_ACCEPTABLE`, its problem as `data`) and closed, without reading further: they are streamed because they may not fit in memory |
|
|
1416
|
+
|
|
1417
|
+
Two routes with one `operationId` are refused, as `mountExpress` refuses them: one procedure
|
|
1418
|
+
would hide the other.
|
|
1419
|
+
|
|
1420
|
+
## tRPC procedures
|
|
1421
|
+
|
|
1422
|
+
The same door for a client of tRPC. `trpcRouter` turns each route into a tRPC procedure named by
|
|
1423
|
+
its `operationId`, a query for a `GET` route and a mutation for the other methods, which the
|
|
1424
|
+
adapters of `@trpc/server` (11.10 or later, an optional peer) serve under an endpoint such as
|
|
1425
|
+
`/trpc`. Each call runs through `executeRoute` with the options of the HTTP adapter, as a call of
|
|
1426
|
+
`orpcRouter` does.
|
|
1427
|
+
|
|
1428
|
+
<!-- checked sample -->
|
|
1429
|
+
```ts
|
|
1430
|
+
import express from 'express';
|
|
1431
|
+
import type { ExecuteOptions, Route } from '@ddd-ts-kit/http';
|
|
1432
|
+
import { mountExpress } from '@ddd-ts-kit/http/express';
|
|
1433
|
+
import { trpcRouter } from '@ddd-ts-kit/http/trpc';
|
|
1434
|
+
import { createExpressMiddleware } from '@trpc/server/adapters/express';
|
|
1435
|
+
|
|
1436
|
+
declare const routes: readonly Route[];
|
|
1437
|
+
declare const options: ExecuteOptions;
|
|
1438
|
+
|
|
1439
|
+
const app = express();
|
|
1440
|
+
|
|
1441
|
+
app.use(express.json()); // tRPC reads the body Express already parsed
|
|
1442
|
+
app.use(
|
|
1443
|
+
'/trpc',
|
|
1444
|
+
createExpressMiddleware({
|
|
1445
|
+
router: trpcRouter(routes, options),
|
|
1446
|
+
createContext: ({ req }) => ({ headers: req.headers, raw: req }),
|
|
1447
|
+
}),
|
|
1448
|
+
);
|
|
1449
|
+
mountExpress(app, routes, options);
|
|
1450
|
+
```
|
|
1451
|
+
|
|
1452
|
+
The context of a call is `TrpcContext`, the same as `OrpcContext`. Fastify
|
|
1453
|
+
(`@trpc/server/adapters/fastify`), Hono (`@trpc/server/adapters/fetch`) and NestJS on Express
|
|
1454
|
+
(`@trpc/server/adapters/standalone`) mount it the same way; `ddd-ts-kit init --rpc trpc` writes
|
|
1455
|
+
the mount for the framework of the project, and `ddd-ts-kit sdk` gives each client the type of
|
|
1456
|
+
the router, at `<client>/trpc`. Mount it as a router of its own, not merged into another: tRPC formats an
|
|
1457
|
+
error with the formatter of the router it serves, and the one of `trpcRouter` is what puts the
|
|
1458
|
+
problem document in `data.problem`.
|
|
1459
|
+
|
|
1460
|
+
| | Over `/trpc` |
|
|
1461
|
+
|---|---|
|
|
1462
|
+
| Procedure | a query for a `GET` route (`client.getOrder.query(input)`), a mutation for the other methods (`client.placeOrder.mutate(input)`) |
|
|
1463
|
+
| Input | `{ path, query, header, body }`, as over `/rpc` |
|
|
1464
|
+
| Answer | the body of the success, as JSON writes it |
|
|
1465
|
+
| Refusal | a `TRPCError` of the code tRPC has for the status (`UNAUTHORIZED` for 401, `NOT_FOUND` for 404, `CONFLICT` for 409, `UNPROCESSABLE_CONTENT` for 422; `BAD_REQUEST` or `INTERNAL_SERVER_ERROR` for a status it has no code for), the `detail` (or `title`) of the problem as `message`, and the problem document as `data.problem`. tRPC has a fixed set of codes: the `code` of the problem, the one of the kit, is what a client tells refusals apart by. `data.problem` is `null` for a refusal the handler answers without a problem document (its message is `HTTP_<status>`) and for an error of tRPC itself, such as an unknown procedure. The stack tRPC adds in development is left out |
|
|
1466
|
+
| `If-Match`, headers of the answer, representations, uploads and raw bodies | as over `/rpc` |
|
|
1467
|
+
| File, list streamed as it is read, binary body | refused with 406 (`NOT_ACCEPTABLE` in `data.problem`) and closed: tRPC answers JSON only |
|
|
1468
|
+
|
|
1250
1469
|
## OpenAPI 3.1
|
|
1251
1470
|
|
|
1252
1471
|
<!-- checked sample -->
|
|
@@ -1499,6 +1718,11 @@ writes a file, and a route that declares no body schema is never refused 406.
|
|
|
1499
1718
|
the client sees a truncated body, and `onError` is told. The items of a stream are not checked
|
|
1500
1719
|
one by one by `validateResponses`.
|
|
1501
1720
|
- CSV is written, never read, and holds flat rows only.
|
|
1721
|
+
- An oRPC or tRPC procedure answers its body only: what a route says in its headers (an `ETag`, a
|
|
1722
|
+
cache policy, a `Location`) stays with the HTTP route, and so do uploads, raw bodies, files,
|
|
1723
|
+
lists streamed as they are read and representations other than JSON (see "oRPC procedures");
|
|
1724
|
+
over tRPC, binary bodies too, and a refusal has the code tRPC has for its status, the code of
|
|
1725
|
+
the kit being in `data.problem`.
|
|
1502
1726
|
- A form describes scalars, nested objects and lists of a closed vocabulary; a list of objects
|
|
1503
1727
|
is a `list` field with no detail. Layout beyond groups and order is the front end's. A lookup
|
|
1504
1728
|
names the route of the options; how the front end calls it and labels its items is its own.
|
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import type { Readable } from 'node:stream';
|
|
1
2
|
import type { Actor } from '@ddd-ts-kit/kernel';
|
|
2
3
|
import type { HandlerInput } from '../route/handler-input.js';
|
|
3
4
|
import type { IncomingFile } from '../route/incoming-file.js';
|
|
5
|
+
import type { RequestContext } from '../route/request-context.js';
|
|
4
6
|
import type { UploadSpec } from '../route/upload-spec.js';
|
|
5
7
|
import type { ControllerSpec } from './controller-spec.js';
|
|
6
8
|
/**
|
|
7
9
|
* What `handle` receives for a given declaration: each part has the type its schema produces,
|
|
8
|
-
* and the actor is the one of the execution context of the request.
|
|
10
|
+
* and the actor is the one of the execution context of the request. With `rawBody`, `context.stream`
|
|
11
|
+
* is the body as it arrived.
|
|
9
12
|
*/
|
|
10
13
|
export type ControllerRequest<Spec extends ControllerSpec = ControllerSpec> = HandlerInput<Spec> & {
|
|
11
14
|
readonly actor: Actor;
|
|
@@ -13,5 +16,11 @@ export type ControllerRequest<Spec extends ControllerSpec = ControllerSpec> = Ha
|
|
|
13
16
|
readonly upload: UploadSpec;
|
|
14
17
|
} ? {
|
|
15
18
|
readonly upload: IncomingFile;
|
|
19
|
+
} : unknown) & (Spec extends {
|
|
20
|
+
readonly rawBody: true;
|
|
21
|
+
} ? {
|
|
22
|
+
readonly context: RequestContext & {
|
|
23
|
+
readonly stream: Readable;
|
|
24
|
+
};
|
|
16
25
|
} : unknown);
|
|
17
26
|
//# sourceMappingURL=controller-request.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-request.d.ts","sourceRoot":"","sources":["../../src/controller/controller-request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD
|
|
1
|
+
{"version":3,"file":"controller-request.d.ts","sourceRoot":"","sources":["../../src/controller/controller-request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,CAAC,IAAI,SAAS,cAAc,GAAG,cAAc,IAAI,YAAY,CAAC,IAAI,CAAC,GAAG;IACjG,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;CACvB,GAAG,CAAC,IAAI,SAAS;IAAE,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAA;CAAE,GAAG;IAAE,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAA;CAAE,GAAG,OAAO,CAAC,GAC9F,CAAC,IAAI,SAAS;IAAE,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAA;CAAE,GACpC;IAAE,QAAQ,CAAC,OAAO,EAAE,cAAc,GAAG;QAAE,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAA;KAAE,CAAA;CAAE,GACpE,OAAO,CAAC,CAAC"}
|
|
@@ -6,5 +6,11 @@ export interface ControllerResponse {
|
|
|
6
6
|
readonly description?: string;
|
|
7
7
|
/** Left out, the controller answers no body and `handle` returns nothing. */
|
|
8
8
|
readonly body?: Schema<unknown>;
|
|
9
|
+
/**
|
|
10
|
+
* The headers the answer carries, each with what it holds: `{ Location: 'The URL of the incident.' }`.
|
|
11
|
+
* The contract lists them, and `handle` then returns `{ body, headers }` (`{ headers }` with no
|
|
12
|
+
* body) with every one of them written.
|
|
13
|
+
*/
|
|
14
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
9
15
|
}
|
|
10
16
|
//# sourceMappingURL=controller-response.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-response.d.ts","sourceRoot":"","sources":["../../src/controller/controller-response.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAErD,iEAAiE;AACjE,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,+DAA+D;IAC/D,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,6EAA6E;IAC7E,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"controller-response.d.ts","sourceRoot":"","sources":["../../src/controller/controller-response.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAErD,iEAAiE;AACjE,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,+DAA+D;IAC/D,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,6EAA6E;IAC7E,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IAChC;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACrD"}
|
|
@@ -1,7 +1,25 @@
|
|
|
1
1
|
import type { Schema } from '@ddd-ts-kit/validation';
|
|
2
2
|
import type { ControllerSpec } from './controller-spec.js';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
type Body<Response> = Response extends {
|
|
4
|
+
readonly body: Schema<infer Value>;
|
|
5
|
+
} ? Value : undefined;
|
|
6
|
+
type Headers<Response> = Response extends {
|
|
7
|
+
readonly headers: infer Declared;
|
|
8
|
+
} ? {
|
|
9
|
+
readonly [Name in keyof Declared]: string;
|
|
10
|
+
} : undefined;
|
|
11
|
+
/**
|
|
12
|
+
* What `handle` returns for a given declaration: the body its response schema describes, or
|
|
13
|
+
* nothing; and, when the response declares headers, `{ body, headers }` (`{ headers }` with no
|
|
14
|
+
* body), every declared header written.
|
|
15
|
+
*/
|
|
16
|
+
export type ControllerResult<Spec extends ControllerSpec = ControllerSpec> = [Headers<Spec['response']>] extends [
|
|
17
|
+
undefined
|
|
18
|
+
] ? Body<Spec['response']> : [Body<Spec['response']>] extends [undefined] ? {
|
|
19
|
+
readonly headers: Headers<Spec['response']>;
|
|
20
|
+
} : {
|
|
21
|
+
readonly body: Body<Spec['response']>;
|
|
22
|
+
readonly headers: Headers<Spec['response']>;
|
|
23
|
+
};
|
|
24
|
+
export {};
|
|
7
25
|
//# sourceMappingURL=controller-result.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-result.d.ts","sourceRoot":"","sources":["../../src/controller/controller-result.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,
|
|
1
|
+
{"version":3,"file":"controller-result.d.ts","sourceRoot":"","sources":["../../src/controller/controller-result.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,KAAK,IAAI,CAAC,QAAQ,IAAI,QAAQ,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,KAAK,CAAC,CAAA;CAAE,GAAG,KAAK,GAAG,SAAS,CAAC;AAElG,KAAK,OAAO,CAAC,QAAQ,IAAI,QAAQ,SAAS;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,QAAQ,CAAA;CAAE,GAC1E;IAAE,QAAQ,EAAE,IAAI,IAAI,MAAM,QAAQ,GAAG,MAAM;CAAE,GAC7C,SAAS,CAAC;AAEd;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,CAAC,IAAI,SAAS,cAAc,GAAG,cAAc,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS;IAC/G,SAAS;CACV,GACG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,GACtB,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,GAC1C;IAAE,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAA;CAAE,GAC/C;IAAE,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAA;CAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-routes.d.ts","sourceRoot":"","sources":["../../src/controller/controller-routes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"controller-routes.d.ts","sourceRoot":"","sources":["../../src/controller/controller-routes.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AAS3E;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,WAAW,EAAE,SAAS,CAAC,eAAe,GAAG,gBAAgB,CAAC,EAAE,EAC5D,OAAO,GAAE,uBAA4B,GACpC,SAAS,KAAK,EAAE,CAMlB"}
|