forjajs 1.1.5 → 1.2.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/CHANGELOG.md +50 -0
- package/README.en.md +310 -0
- package/README.md +37 -6
- package/bin/forja.mjs +3 -3
- package/boilerplates/06-clean-arch/README.md +48 -0
- package/boilerplates/06-clean-arch/WHEN-CLEAN-WHEN-LEAN.md +42 -0
- package/boilerplates/06-clean-arch/backend/package.json +43 -0
- package/boilerplates/06-clean-arch/backend/src/app.module.ts +20 -0
- package/boilerplates/06-clean-arch/backend/src/main.ts +10 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/application/place-order.usecase.ts +47 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/application/ship-order.usecase.ts +28 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/money.vo.ts +30 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order-status.vo.ts +36 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.entity.ts +85 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.repository.ts +17 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/infrastructure/order.orm-entity.ts +24 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/infrastructure/typeorm-order.repository.ts +57 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/orders.module.ts +28 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.controller.ts +31 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.http.dto.ts +30 -0
- package/boilerplates/06-clean-arch/backend/src/modules/products/product.entity.ts +20 -0
- package/boilerplates/06-clean-arch/backend/src/modules/products/products.controller.ts +43 -0
- package/boilerplates/06-clean-arch/backend/src/modules/products/products.module.ts +11 -0
- package/boilerplates/06-clean-arch/backend/src/shared/result.ts +32 -0
- package/boilerplates/06-clean-arch/backend/test/orders/place-order.spec.ts +46 -0
- package/boilerplates/06-clean-arch/backend/tsconfig.json +16 -0
- package/boilerplates/06-clean-arch/boilerplate.manifest.json +43 -0
- package/boilerplates/06-clean-arch/memory/30-domains/orders/context.md +39 -0
- package/boilerplates/06-clean-arch/memory/30-domains/products/context.md +23 -0
- package/boilerplates/README.md +20 -0
- package/docs/personas/architect/README.md +4 -4
- package/docs/personas/developer/README.md +3 -3
- package/docs/personas/qa/README.md +3 -3
- package/docs/quick-reference.md +9 -9
- package/docs/structure.md +3 -3
- package/lib/core/checks.mjs +20 -3
- package/lib/core/doc-graph.mjs +231 -0
- package/lib/core/health.mjs +131 -29
- package/lib/core/registry.mjs +23 -0
- package/lib/core/release.mjs +48 -8
- package/lib/templates/harness/code-intel.mjs +2 -2
- package/memory/90-decisions/0025-coerencia-da-documentacao.md +95 -0
- package/memory/90-decisions/0027-clean-arch-calibrada.md +96 -0
- package/package.json +8 -1
- package/scripts/agent-harness.mjs +7 -5
- package/scripts/context-ops.mjs +7 -4
- package/scripts/dev.mjs +2 -2
- package/scripts/hook-guard-paths.mjs +1 -0
- package/scripts/hook-user-prompt.mjs +1 -1
- package/scripts/spec-cli.mjs +4 -3
- package/scripts/tools-doctor.mjs +1 -1
- package/specs/clean-arch-boilerplate/plan.md +137 -0
- package/specs/clean-arch-boilerplate/spec.md +121 -0
- package/specs/clean-arch-boilerplate/tasks.md +70 -0
- package/specs/coerencia-do-sistema/plan.md +155 -0
- package/specs/coerencia-do-sistema/spec.md +15 -14
- package/specs/coerencia-do-sistema/tasks.md +115 -0
- package/specs/ts-migration/plan.md +188 -0
- package/specs/ts-migration/spec.md +119 -0
- package/specs/ts-migration/tasks.md +110 -0
package/boilerplates/06-clean-arch/backend/src/modules/orders/application/place-order.usecase.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Inject, Injectable } from '@nestjs/common';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { Order, OrderLine } from '../domain/order.entity';
|
|
4
|
+
import { Money } from '../domain/money.vo';
|
|
5
|
+
import { ORDER_REPOSITORY, OrderRepository } from '../domain/order.repository';
|
|
6
|
+
import { Result } from '../../../shared/result';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Contratos de entrada/saída — tipados e legíveis. Um agente entende o que o use-case faz pela
|
|
10
|
+
* assinatura, **sem ler o corpo** (AC-5). É a compressão de contexto: o tipo é o resumo.
|
|
11
|
+
*/
|
|
12
|
+
export interface PlaceOrderInput {
|
|
13
|
+
customerId: string;
|
|
14
|
+
items: Array<{ productId: string; unitPriceCents: number; quantity: number }>;
|
|
15
|
+
}
|
|
16
|
+
export interface PlaceOrderOutput {
|
|
17
|
+
orderId: string;
|
|
18
|
+
totalCents: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* PlaceOrder — orquestra o domínio + a porta. O use-case não tem regra de negócio própria: ele
|
|
23
|
+
* traduz o input, chama o agregado (que decide), e persiste via porta. A regra ("precisa de itens")
|
|
24
|
+
* é do `Order`, não daqui.
|
|
25
|
+
*/
|
|
26
|
+
@Injectable()
|
|
27
|
+
export class PlaceOrderUseCase {
|
|
28
|
+
// Injeta a PORTA (token), nunca o adapter concreto — a inversão de dependência.
|
|
29
|
+
constructor(@Inject(ORDER_REPOSITORY) private readonly orders: OrderRepository) {}
|
|
30
|
+
|
|
31
|
+
async execute(input: PlaceOrderInput): Promise<Result<PlaceOrderOutput>> {
|
|
32
|
+
const lines: OrderLine[] = input.items.map((i) => ({
|
|
33
|
+
productId: i.productId,
|
|
34
|
+
unitPrice: Money.of(i.unitPriceCents),
|
|
35
|
+
quantity: i.quantity,
|
|
36
|
+
}));
|
|
37
|
+
|
|
38
|
+
const created = Order.place(randomUUID(), input.customerId, lines);
|
|
39
|
+
if (created.isFailure) return Result.fail(created.error!);
|
|
40
|
+
|
|
41
|
+
const order = created.value;
|
|
42
|
+
order.confirm(); // rascunho → confirmado (a máquina de estados do domínio valida)
|
|
43
|
+
await this.orders.save(order);
|
|
44
|
+
|
|
45
|
+
return Result.ok({ orderId: order.id, totalCents: order.total.cents });
|
|
46
|
+
}
|
|
47
|
+
}
|
package/boilerplates/06-clean-arch/backend/src/modules/orders/application/ship-order.usecase.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Inject, Injectable } from '@nestjs/common';
|
|
2
|
+
import { ORDER_REPOSITORY, OrderRepository } from '../domain/order.repository';
|
|
3
|
+
import { Result } from '../../../shared/result';
|
|
4
|
+
|
|
5
|
+
export interface ShipOrderInput {
|
|
6
|
+
orderId: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* ShipOrder — demonstra a invariante-chave passando pelo domínio: `order.ship()` **falha** se o
|
|
11
|
+
* pedido não estiver PAID. O use-case não reimplementa a regra; ele confia no agregado e propaga a
|
|
12
|
+
* falha. A regra "não envia sem pagamento" existe num lugar só: `Order`.
|
|
13
|
+
*/
|
|
14
|
+
@Injectable()
|
|
15
|
+
export class ShipOrderUseCase {
|
|
16
|
+
constructor(@Inject(ORDER_REPOSITORY) private readonly orders: OrderRepository) {}
|
|
17
|
+
|
|
18
|
+
async execute(input: ShipOrderInput): Promise<Result<void>> {
|
|
19
|
+
const order = await this.orders.byId(input.orderId);
|
|
20
|
+
if (!order) return Result.fail('pedido não encontrado');
|
|
21
|
+
|
|
22
|
+
const shipped = order.ship(); // domínio decide: só sai de PAID
|
|
23
|
+
if (shipped.isFailure) return Result.fail(shipped.error!);
|
|
24
|
+
|
|
25
|
+
await this.orders.save(order);
|
|
26
|
+
return Result.ok(undefined);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Money — value object. Imutável, comparado por valor, valida a si mesmo na criação.
|
|
3
|
+
* Zero dependência de framework: é TypeScript puro (o ponto do domínio isolado).
|
|
4
|
+
*/
|
|
5
|
+
export class Money {
|
|
6
|
+
private constructor(public readonly cents: number) {}
|
|
7
|
+
|
|
8
|
+
static of(cents: number): Money {
|
|
9
|
+
if (!Number.isInteger(cents) || cents < 0) {
|
|
10
|
+
throw new Error('Money exige inteiro não-negativo em centavos');
|
|
11
|
+
}
|
|
12
|
+
return new Money(cents);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
static zero(): Money {
|
|
16
|
+
return new Money(0);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
plus(other: Money): Money {
|
|
20
|
+
return new Money(this.cents + other.cents);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
times(qty: number): Money {
|
|
24
|
+
return Money.of(this.cents * qty);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
isZero(): boolean {
|
|
28
|
+
return this.cents === 0;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OrderStatus — value object que é uma máquina de estados. As transições legais moram AQUI, no
|
|
3
|
+
* domínio, não num `if` espalhado pelos services. Um estado inválido é impossível de construir.
|
|
4
|
+
*
|
|
5
|
+
* DRAFT ──confirm──► CONFIRMED ──pay──► PAID ──ship──► SHIPPED
|
|
6
|
+
* └──────────────── cancel ──────────────► CANCELLED (de qualquer não-enviado)
|
|
7
|
+
*/
|
|
8
|
+
export type OrderStatusValue = 'DRAFT' | 'CONFIRMED' | 'PAID' | 'SHIPPED' | 'CANCELLED';
|
|
9
|
+
|
|
10
|
+
const TRANSITIONS: Record<OrderStatusValue, OrderStatusValue[]> = {
|
|
11
|
+
DRAFT: ['CONFIRMED', 'CANCELLED'],
|
|
12
|
+
CONFIRMED: ['PAID', 'CANCELLED'],
|
|
13
|
+
PAID: ['SHIPPED', 'CANCELLED'],
|
|
14
|
+
SHIPPED: [],
|
|
15
|
+
CANCELLED: [],
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export class OrderStatus {
|
|
19
|
+
private constructor(public readonly value: OrderStatusValue) {}
|
|
20
|
+
|
|
21
|
+
static draft(): OrderStatus {
|
|
22
|
+
return new OrderStatus('DRAFT');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
static from(value: OrderStatusValue): OrderStatus {
|
|
26
|
+
return new OrderStatus(value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
canTransitionTo(next: OrderStatusValue): boolean {
|
|
30
|
+
return TRANSITIONS[this.value].includes(next);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
is(value: OrderStatusValue): boolean {
|
|
34
|
+
return this.value === value;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { Result } from '../../../shared/result';
|
|
2
|
+
import { Money } from './money.vo';
|
|
3
|
+
import { OrderStatus } from './order-status.vo';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Order — o agregado. **Toda invariante de negócio mora aqui**, em TypeScript puro:
|
|
7
|
+
*
|
|
8
|
+
* - não confirma um pedido sem itens;
|
|
9
|
+
* - não paga o que não foi confirmado; não envia o que não foi pago;
|
|
10
|
+
* - o total é derivado das linhas, nunca setado de fora.
|
|
11
|
+
*
|
|
12
|
+
* Nenhum import de `@nestjs` ou de ORM. É isso que torna `place-order.spec.ts` capaz de testar a
|
|
13
|
+
* regra instanciando só este objeto — sem subir o Nest. Se um dia precisar do framework para testar
|
|
14
|
+
* a invariante, o domínio vazou.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export interface OrderLine {
|
|
18
|
+
readonly productId: string;
|
|
19
|
+
readonly unitPrice: Money;
|
|
20
|
+
readonly quantity: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class Order {
|
|
24
|
+
private constructor(
|
|
25
|
+
public readonly id: string,
|
|
26
|
+
public readonly customerId: string,
|
|
27
|
+
private _lines: OrderLine[],
|
|
28
|
+
private _status: OrderStatus,
|
|
29
|
+
) {}
|
|
30
|
+
|
|
31
|
+
/** Cria um pedido em rascunho. Regra: precisa de ao menos uma linha. */
|
|
32
|
+
static place(id: string, customerId: string, lines: OrderLine[]): Result<Order> {
|
|
33
|
+
if (lines.length === 0) {
|
|
34
|
+
return Result.fail('um pedido precisa de ao menos um item');
|
|
35
|
+
}
|
|
36
|
+
if (lines.some((l) => l.quantity <= 0)) {
|
|
37
|
+
return Result.fail('quantidade de item deve ser positiva');
|
|
38
|
+
}
|
|
39
|
+
return Result.ok(new Order(id, customerId, [...lines], OrderStatus.draft()));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Reconstrói do estado persistido (usado pelo mapper da infra — sem revalidar regra de criação). */
|
|
43
|
+
static rehydrate(id: string, customerId: string, lines: OrderLine[], status: OrderStatus): Order {
|
|
44
|
+
return new Order(id, customerId, lines, status);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
get status(): OrderStatus {
|
|
48
|
+
return this._status;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
get lines(): readonly OrderLine[] {
|
|
52
|
+
return this._lines;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Total derivado das linhas — nunca um campo setável de fora. */
|
|
56
|
+
get total(): Money {
|
|
57
|
+
return this._lines.reduce((acc, l) => acc.plus(l.unitPrice.times(l.quantity)), Money.zero());
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
confirm(): Result<void> {
|
|
61
|
+
return this.transition('CONFIRMED');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Invariante-chave: só paga o confirmado. */
|
|
65
|
+
pay(): Result<void> {
|
|
66
|
+
return this.transition('PAID');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Invariante-chave: **não envia sem pagamento**. A transição só é legal a partir de PAID. */
|
|
70
|
+
ship(): Result<void> {
|
|
71
|
+
return this.transition('SHIPPED');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
cancel(): Result<void> {
|
|
75
|
+
return this.transition('CANCELLED');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private transition(to: Parameters<OrderStatus['canTransitionTo']>[0]): Result<void> {
|
|
79
|
+
if (!this._status.canTransitionTo(to)) {
|
|
80
|
+
return Result.fail(`transição inválida: ${this._status.value} → ${to}`);
|
|
81
|
+
}
|
|
82
|
+
this._status = OrderStatus.from(to);
|
|
83
|
+
return Result.ok(undefined);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Order } from './order.entity';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* OrderRepository — a **PORTA** (Clean Architecture / Hexagonal). É uma `interface` no domínio: o
|
|
5
|
+
* domínio declara o que precisa de persistência, sem saber *como*. O adapter (TypeORM, in-memory,
|
|
6
|
+
* outro) a implementa na camada de infraestrutura.
|
|
7
|
+
*
|
|
8
|
+
* `ORDER_REPOSITORY` é o token de injeção do NestJS — porque interface não existe em runtime, o Nest
|
|
9
|
+
* injeta por token. O use-case pede o token; o módulo faz o bind token→adapter. É assim que a
|
|
10
|
+
* dependência aponta para DENTRO: application → domain, e a infra implementa a porta do domínio.
|
|
11
|
+
*/
|
|
12
|
+
export const ORDER_REPOSITORY = Symbol('OrderRepository');
|
|
13
|
+
|
|
14
|
+
export interface OrderRepository {
|
|
15
|
+
save(order: Order): Promise<void>;
|
|
16
|
+
byId(id: string): Promise<Order | null>;
|
|
17
|
+
}
|
package/boilerplates/06-clean-arch/backend/src/modules/orders/infrastructure/order.orm-entity.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Column, Entity, PrimaryColumn } from 'typeorm';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* OrderOrmEntity — a forma de PERSISTÊNCIA, decorada com TypeORM. Vive só na infraestrutura.
|
|
5
|
+
*
|
|
6
|
+
* Repare: **não é** o `Order` do domínio. O agregado de domínio é TypeScript puro, sem `@Entity`. O
|
|
7
|
+
* mapper (no repositório) traduz entre os dois. É essa separação que mantém o ORM fora do domínio —
|
|
8
|
+
* trocar o TypeORM por outra coisa mexe só aqui.
|
|
9
|
+
*/
|
|
10
|
+
@Entity('orders')
|
|
11
|
+
export class OrderOrmEntity {
|
|
12
|
+
@PrimaryColumn('uuid')
|
|
13
|
+
id!: string;
|
|
14
|
+
|
|
15
|
+
@Column()
|
|
16
|
+
customerId!: string;
|
|
17
|
+
|
|
18
|
+
@Column()
|
|
19
|
+
status!: string;
|
|
20
|
+
|
|
21
|
+
/** Linhas serializadas — detalhe de persistência, não modelagem de domínio. */
|
|
22
|
+
@Column('jsonb')
|
|
23
|
+
lines!: Array<{ productId: string; unitPriceCents: number; quantity: number }>;
|
|
24
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { InjectRepository } from '@nestjs/typeorm';
|
|
3
|
+
import { Repository } from 'typeorm';
|
|
4
|
+
import { Order, OrderLine } from '../domain/order.entity';
|
|
5
|
+
import { Money } from '../domain/money.vo';
|
|
6
|
+
import { OrderStatus, OrderStatusValue } from '../domain/order-status.vo';
|
|
7
|
+
import { OrderRepository } from '../domain/order.repository';
|
|
8
|
+
import { OrderOrmEntity } from './order.orm-entity';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* O ADAPTER: implementa a porta `OrderRepository` do domínio usando TypeORM. É o único lugar que
|
|
12
|
+
* conhece o ORM. O **mapper** (toDomain/toOrm) traduz entre o agregado puro e a orm-entity — a
|
|
13
|
+
* fronteira que impede o TypeORM de vazar para dentro.
|
|
14
|
+
*/
|
|
15
|
+
@Injectable()
|
|
16
|
+
export class TypeOrmOrderRepository implements OrderRepository {
|
|
17
|
+
constructor(
|
|
18
|
+
@InjectRepository(OrderOrmEntity)
|
|
19
|
+
private readonly repo: Repository<OrderOrmEntity>,
|
|
20
|
+
) {}
|
|
21
|
+
|
|
22
|
+
async save(order: Order): Promise<void> {
|
|
23
|
+
await this.repo.save(this.toOrm(order));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async byId(id: string): Promise<Order | null> {
|
|
27
|
+
const row = await this.repo.findOne({ where: { id } });
|
|
28
|
+
return row ? this.toDomain(row) : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
private toOrm(order: Order): OrderOrmEntity {
|
|
32
|
+
const row = new OrderOrmEntity();
|
|
33
|
+
row.id = order.id;
|
|
34
|
+
row.customerId = order.customerId;
|
|
35
|
+
row.status = order.status.value;
|
|
36
|
+
row.lines = order.lines.map((l) => ({
|
|
37
|
+
productId: l.productId,
|
|
38
|
+
unitPriceCents: l.unitPrice.cents,
|
|
39
|
+
quantity: l.quantity,
|
|
40
|
+
}));
|
|
41
|
+
return row;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private toDomain(row: OrderOrmEntity): Order {
|
|
45
|
+
const lines: OrderLine[] = row.lines.map((l) => ({
|
|
46
|
+
productId: l.productId,
|
|
47
|
+
unitPrice: Money.of(l.unitPriceCents),
|
|
48
|
+
quantity: l.quantity,
|
|
49
|
+
}));
|
|
50
|
+
return Order.rehydrate(
|
|
51
|
+
row.id,
|
|
52
|
+
row.customerId,
|
|
53
|
+
lines,
|
|
54
|
+
OrderStatus.from(row.status as OrderStatusValue),
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
3
|
+
import { ORDER_REPOSITORY } from './domain/order.repository';
|
|
4
|
+
import { OrderOrmEntity } from './infrastructure/order.orm-entity';
|
|
5
|
+
import { TypeOrmOrderRepository } from './infrastructure/typeorm-order.repository';
|
|
6
|
+
import { PlaceOrderUseCase } from './application/place-order.usecase';
|
|
7
|
+
import { ShipOrderUseCase } from './application/ship-order.usecase';
|
|
8
|
+
import { OrdersController } from './presentation/orders.controller';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* O módulo é onde a **inversão de dependência** acontece, numa linha:
|
|
12
|
+
*
|
|
13
|
+
* { provide: ORDER_REPOSITORY, useClass: TypeOrmOrderRepository }
|
|
14
|
+
*
|
|
15
|
+
* O use-case pede o token `ORDER_REPOSITORY` (a porta do domínio); o Nest entrega o adapter TypeORM.
|
|
16
|
+
* Trocar de persistência = trocar o `useClass` aqui, e nada mais. O domínio e a aplicação não sabem
|
|
17
|
+
* que TypeORM existe.
|
|
18
|
+
*/
|
|
19
|
+
@Module({
|
|
20
|
+
imports: [TypeOrmModule.forFeature([OrderOrmEntity])],
|
|
21
|
+
controllers: [OrdersController],
|
|
22
|
+
providers: [
|
|
23
|
+
PlaceOrderUseCase,
|
|
24
|
+
ShipOrderUseCase,
|
|
25
|
+
{ provide: ORDER_REPOSITORY, useClass: TypeOrmOrderRepository },
|
|
26
|
+
],
|
|
27
|
+
})
|
|
28
|
+
export class OrdersModule {}
|
package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.controller.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { BadRequestException, Body, Controller, Param, Post } from '@nestjs/common';
|
|
2
|
+
import { PlaceOrderUseCase } from '../application/place-order.usecase';
|
|
3
|
+
import { ShipOrderUseCase } from '../application/ship-order.usecase';
|
|
4
|
+
import { PlaceOrderHttpDto } from './orders.http.dto';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* O controller é FINO. Ele traduz HTTP↔use-case e converte falha de domínio em erro HTTP — nada
|
|
8
|
+
* mais. Zero regra de negócio aqui. Se você sentir vontade de colocar um `if` de regra no
|
|
9
|
+
* controller, ele pertence ao domínio.
|
|
10
|
+
*/
|
|
11
|
+
@Controller('orders')
|
|
12
|
+
export class OrdersController {
|
|
13
|
+
constructor(
|
|
14
|
+
private readonly placeOrder: PlaceOrderUseCase,
|
|
15
|
+
private readonly shipOrder: ShipOrderUseCase,
|
|
16
|
+
) {}
|
|
17
|
+
|
|
18
|
+
@Post()
|
|
19
|
+
async place(@Body() dto: PlaceOrderHttpDto) {
|
|
20
|
+
const result = await this.placeOrder.execute(dto);
|
|
21
|
+
if (result.isFailure) throw new BadRequestException(result.error);
|
|
22
|
+
return result.value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
@Post(':id/ship')
|
|
26
|
+
async ship(@Param('id') id: string) {
|
|
27
|
+
const result = await this.shipOrder.execute({ orderId: id });
|
|
28
|
+
if (result.isFailure) throw new BadRequestException(result.error);
|
|
29
|
+
return { ok: true };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { IsArray, IsInt, IsPositive, IsString, ValidateNested } from 'class-validator';
|
|
2
|
+
import { Type } from 'class-transformer';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* DTOs de HTTP — a forma do que chega pela borda. Validados com class-validator. São de
|
|
6
|
+
* PRESENTAÇÃO: o controller os traduz para o input do use-case. O domínio nunca vê estes tipos.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
class OrderItemDto {
|
|
10
|
+
@IsString()
|
|
11
|
+
productId!: string;
|
|
12
|
+
|
|
13
|
+
@IsInt()
|
|
14
|
+
@IsPositive()
|
|
15
|
+
unitPriceCents!: number;
|
|
16
|
+
|
|
17
|
+
@IsInt()
|
|
18
|
+
@IsPositive()
|
|
19
|
+
quantity!: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class PlaceOrderHttpDto {
|
|
23
|
+
@IsString()
|
|
24
|
+
customerId!: string;
|
|
25
|
+
|
|
26
|
+
@IsArray()
|
|
27
|
+
@ValidateNested({ each: true })
|
|
28
|
+
@Type(() => OrderItemDto)
|
|
29
|
+
items!: OrderItemDto[];
|
|
30
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Product — CRUD puro, SEM regra de negócio. Aqui a orm-entity É o modelo: não há invariante para
|
|
5
|
+
* proteger, então separar domínio/persistência seria custo sem retorno. Uma classe, decorada.
|
|
6
|
+
*
|
|
7
|
+
* Este é o **caminho enxuto** (AC-4). Compare com `modules/orders/`: lá, quatro camadas porque há
|
|
8
|
+
* regra que se paga; aqui, uma, porque não há. Ver `WHEN-CLEAN-WHEN-LEAN.md`.
|
|
9
|
+
*/
|
|
10
|
+
@Entity('products')
|
|
11
|
+
export class Product {
|
|
12
|
+
@PrimaryGeneratedColumn('uuid')
|
|
13
|
+
id!: string;
|
|
14
|
+
|
|
15
|
+
@Column()
|
|
16
|
+
name!: string;
|
|
17
|
+
|
|
18
|
+
@Column('int')
|
|
19
|
+
priceCents!: number;
|
|
20
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
|
2
|
+
import { InjectRepository } from '@nestjs/typeorm';
|
|
3
|
+
import { Repository } from 'typeorm';
|
|
4
|
+
import { IsInt, IsPositive, IsString } from 'class-validator';
|
|
5
|
+
import { Product } from './product.entity';
|
|
6
|
+
|
|
7
|
+
class CreateProductDto {
|
|
8
|
+
@IsString()
|
|
9
|
+
name!: string;
|
|
10
|
+
|
|
11
|
+
@IsInt()
|
|
12
|
+
@IsPositive()
|
|
13
|
+
priceCents!: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* CRUD enxuto: o controller fala DIRETO com o repositório do TypeORM. Sem use-case, sem porta, sem
|
|
18
|
+
* mapper. Para dados sem invariante, essas camadas seriam só arquivos a mais para o dev e para o
|
|
19
|
+
* agente lerem — o oposto de economia de token.
|
|
20
|
+
*
|
|
21
|
+
* A regra de quando promover isto para o padrão de `orders/` está em `WHEN-CLEAN-WHEN-LEAN.md`.
|
|
22
|
+
*/
|
|
23
|
+
@Controller('products')
|
|
24
|
+
export class ProductsController {
|
|
25
|
+
constructor(
|
|
26
|
+
@InjectRepository(Product) private readonly repo: Repository<Product>,
|
|
27
|
+
) {}
|
|
28
|
+
|
|
29
|
+
@Post()
|
|
30
|
+
create(@Body() dto: CreateProductDto) {
|
|
31
|
+
return this.repo.save(this.repo.create(dto));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
@Get()
|
|
35
|
+
list() {
|
|
36
|
+
return this.repo.find();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
@Get(':id')
|
|
40
|
+
byId(@Param('id') id: string) {
|
|
41
|
+
return this.repo.findOne({ where: { id } });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
3
|
+
import { Product } from './product.entity';
|
|
4
|
+
import { ProductsController } from './products.controller';
|
|
5
|
+
|
|
6
|
+
/** CRUD enxuto: só o controller e a entity. Sem providers de porta/adapter — não há o que inverter. */
|
|
7
|
+
@Module({
|
|
8
|
+
imports: [TypeOrmModule.forFeature([Product])],
|
|
9
|
+
controllers: [ProductsController],
|
|
10
|
+
})
|
|
11
|
+
export class ProductsModule {}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result<T> — sucesso ou falha de domínio, sem lançar exceção.
|
|
3
|
+
*
|
|
4
|
+
* O domínio devolve `Result` em vez de `throw` para que a regra de negócio seja um valor testável
|
|
5
|
+
* (o teste lê `.isFailure`, não captura exceção) e para que a camada de aplicação decida o que
|
|
6
|
+
* fazer com a falha. `throw` é reservado para o inesperado (bug), não para regra de negócio.
|
|
7
|
+
*/
|
|
8
|
+
export class Result<T> {
|
|
9
|
+
private constructor(
|
|
10
|
+
public readonly isSuccess: boolean,
|
|
11
|
+
private readonly _value?: T,
|
|
12
|
+
public readonly error?: string,
|
|
13
|
+
) {}
|
|
14
|
+
|
|
15
|
+
get isFailure(): boolean {
|
|
16
|
+
return !this.isSuccess;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Só chame após checar `isSuccess`. Falha aqui é bug, não regra. */
|
|
20
|
+
get value(): T {
|
|
21
|
+
if (!this.isSuccess) throw new Error(`Result sem valor: ${this.error}`);
|
|
22
|
+
return this._value as T;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
static ok<T>(value: T): Result<T> {
|
|
26
|
+
return new Result(true, value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
static fail<T>(error: string): Result<T> {
|
|
30
|
+
return new Result<T>(false, undefined, error);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { Order } from '../../src/modules/orders/domain/order.entity';
|
|
2
|
+
import { Money } from '../../src/modules/orders/domain/money.vo';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A prova concreta do isolamento (AC-8): estes testes exercem a **regra de negócio** instanciando
|
|
6
|
+
* SÓ o agregado de domínio — sem `Test.createTestingModule`, sem ORM, sem subir o Nest. Se um dia a
|
|
7
|
+
* invariante precisar do framework para ser testada, o domínio vazou e a arquitetura falhou.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const line = (cents: number, qty: number) => ({
|
|
11
|
+
productId: 'p1',
|
|
12
|
+
unitPrice: Money.of(cents),
|
|
13
|
+
quantity: qty,
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe('Order (domínio, sem Nest)', () => {
|
|
17
|
+
it('não cria pedido sem itens', () => {
|
|
18
|
+
const r = Order.place('o1', 'c1', []);
|
|
19
|
+
expect(r.isFailure).toBe(true);
|
|
20
|
+
expect(r.error).toMatch(/ao menos um item/);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('deriva o total das linhas', () => {
|
|
24
|
+
const order = Order.place('o1', 'c1', [line(1000, 2), line(500, 1)]).value;
|
|
25
|
+
expect(order.total.cents).toBe(2500);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('NÃO envia sem pagamento — a invariante-chave', () => {
|
|
29
|
+
const order = Order.place('o1', 'c1', [line(1000, 1)]).value;
|
|
30
|
+
order.confirm();
|
|
31
|
+
// pula o pay() de propósito
|
|
32
|
+
const shipped = order.ship();
|
|
33
|
+
expect(shipped.isFailure).toBe(true);
|
|
34
|
+
expect(shipped.error).toMatch(/transição inválida/);
|
|
35
|
+
expect(order.status.value).toBe('CONFIRMED');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('envia quando pago — o caminho feliz da máquina de estados', () => {
|
|
39
|
+
const order = Order.place('o1', 'c1', [line(1000, 1)]).value;
|
|
40
|
+
order.confirm();
|
|
41
|
+
order.pay();
|
|
42
|
+
const shipped = order.ship();
|
|
43
|
+
expect(shipped.isSuccess).toBe(true);
|
|
44
|
+
expect(order.status.value).toBe('SHIPPED');
|
|
45
|
+
});
|
|
46
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"module": "commonjs",
|
|
4
|
+
"target": "es2022",
|
|
5
|
+
"moduleResolution": "node",
|
|
6
|
+
"experimentalDecorators": true,
|
|
7
|
+
"emitDecoratorMetadata": true,
|
|
8
|
+
"declaration": false,
|
|
9
|
+
"strict": true,
|
|
10
|
+
"skipLibCheck": true,
|
|
11
|
+
"esModuleInterop": true,
|
|
12
|
+
"outDir": "./dist",
|
|
13
|
+
"baseUrl": "./"
|
|
14
|
+
},
|
|
15
|
+
"include": ["src/**/*", "test/**/*"]
|
|
16
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": "1.0",
|
|
3
|
+
"type": "boilerplate",
|
|
4
|
+
"name": "06-clean-arch",
|
|
5
|
+
"title": "Clean Architecture Calibrada - DDD por camadas, sem cerimônia",
|
|
6
|
+
"path": "boilerplates/06-clean-arch",
|
|
7
|
+
"readme": "boilerplates/06-clean-arch/README.md",
|
|
8
|
+
"stack": [
|
|
9
|
+
"NestJS",
|
|
10
|
+
"TypeScript",
|
|
11
|
+
"TypeORM",
|
|
12
|
+
"Postgres"
|
|
13
|
+
],
|
|
14
|
+
"useCases": [
|
|
15
|
+
"Domínio com regra de negócio",
|
|
16
|
+
"DDD",
|
|
17
|
+
"Clean Architecture",
|
|
18
|
+
"Hexagonal"
|
|
19
|
+
],
|
|
20
|
+
"commands": [
|
|
21
|
+
"npm install",
|
|
22
|
+
"npm run start:dev",
|
|
23
|
+
"npm test",
|
|
24
|
+
"npm run test:e2e"
|
|
25
|
+
],
|
|
26
|
+
"gates": [
|
|
27
|
+
"npm test",
|
|
28
|
+
"npm run test:cov"
|
|
29
|
+
],
|
|
30
|
+
"tokenPolicy": {
|
|
31
|
+
"firstRead": [
|
|
32
|
+
"boilerplate.manifest.json",
|
|
33
|
+
"README.md",
|
|
34
|
+
"WHEN-CLEAN-WHEN-LEAN.md",
|
|
35
|
+
"memory/30-domains/orders/context.md"
|
|
36
|
+
],
|
|
37
|
+
"avoidLoadingByDefault": [
|
|
38
|
+
"node_modules",
|
|
39
|
+
"dist",
|
|
40
|
+
"coverage"
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
}
|