Entities and fields
An entity is a thing your business cares about that has an identity over time: a Producto, a
Pedido, a Cliente. In Puerto, an entity is also the unit of generation. One command writes
it in every layer.
puerto generar scaffold Pedido -- importe:Importe:f64 estado:Estado:enum:Pendiente/Confirmado/Cancelado nota:opt:StringThe name is PascalCase; Puerto derives pedido for the context, the crates and the modules,
pedidos for the table and the routes, and IdPedido for the id. Fields go after --. The
field types reference lists every type and what it becomes in each
layer.
What it writes
Section titled “What it writes”Each entity is a context, contextos/pedido/, with one crate per layer: dominio_pedido
(domain), aplicacion_pedido (application), infra_pedido (infrastructure) and rest_pedido
(the HTTP API), so Cargo enforces the dependency rule
(ADR-0023).
Directorycontextos/pedido/
Directorydominio/src/
- modelo.rs Pedido, IdPedido, PropsPedido, Pedido::new
- valores.rs Importe, Estado
- errores.rs ErrorPedido, with From<ErrorRepositorio>
- repositorio.rs the port, RepositorioPedido, and its double
- pruebas/madres.rs MadrePedido
Directoryaplicacion/src/ crear_pedido, obtener_pedido, listar_pedidos, actualizar_pedido, borrar_pedido: one file each, with its tests
- …
Directoryinfraestructura/src/
- repositorio.rs RepositorioPedidoEnMemoria, or RepositorioPedidoPostgres
- fila.rs the row, with –db
- pruebas/siembra.rs seeds for the Postgres tests, with –db
Directoryrest/src/
- rutas.rs five endpoints, with route tests
- dto.rs
- respuestas.rs
- errores.rs
- migraciones/…_crear_tabla_pedido.sql with –db
Directoryweb/src/…/pedido/ list, detail and form screens, with web projects
- …
Each crate gets its own Cargo.toml and a flat lib.rs. The scaffold also adds the crates to the
root Cargo.toml and to presentacion/api/Cargo.toml, adds the entity to puerto.toml,
regenerates presentacion/cableado/ and presentacion/api/src/generado/bootstrap.rs and, in a
web project, the frontend’s route table. Then it runs cargo fmt.
The five endpoints
Section titled “The five endpoints”| Use case | Route | Success |
|---|---|---|
crear_pedido |
POST /api/pedidos |
201 + the order |
obtener_pedido |
GET /api/pedidos/:id |
200 + the order |
listar_pedidos |
GET /api/pedidos?limite=&desplazamiento= |
200 + a page |
actualizar_pedido |
PUT /api/pedidos/:id |
200 + the order |
borrar_pedido |
DELETE /api/pedidos/:id |
204 |
Lists are pages, { elementos, total, limite, desplazamiento }: 20 items by default, never more
than 100. The cap is a rule of the domain (PeticionPagina), so no route or adapter can ask for
more (ADR-0016). Deletes are soft.
The model is where the rules go
Section titled “The model is where the rules go”Pedido::new is the only way to build a Pedido from outside the repository. It is where
invariants live, and the generated tests show the shape:
impl Producto { pub fn new(props: PropsProducto) -> Result<Self, ErrorProducto> { if props.nombre.trim().is_empty() { return Err(ErrorProducto::Validacion("nombre_vacio".into())); } if props.sku.trim().is_empty() { return Err(ErrorProducto::Validacion("sku_vacio".into())); } let ahora = chrono::Utc::now(); Ok(Self { id: IdProducto::generar(), // … }) }}Required String fields already refuse an empty value. Add your own checks the same way: return
a Validacion with a snake_case code, and the API answers 422 with
producto.validacion.<code>. The web form shows it next to the field when the code names one.
Each entity has its own id type
Section titled “Each entity has its own id type”pub struct IdProducto(Uuid);IdProducto::generar() makes a new one, IdProducto::from_uuid(u) wraps one read from a path or
a row, and .valor() unwraps it at the edges. An IdCliente cannot be passed where an
IdProducto goes. The newtype stops at the boundary: routes take Path<Uuid>, and DTOs and rows
keep a Uuid, so the OpenAPI contract stays string(uuid)
(ADR-0014).
Referring to another entity
Section titled “Referring to another entity”An entity that belongs to another holds its id:
puerto generar scaffold Cliente -- nombre:String email:String!puerto generar scaffold Pedido -- cliente_id:ref:Cliente revisor_id:ref:opt:Cliente total:i64Pedido.cliente_id is an IdCliente, not a Cliente: there is no navigation and no lazy
loading, and a use case that needs the customer asks its repository. The reference is also a
dependency between crates: dominio_pedido depends on dominio_cliente, which owns IdCliente,
so Cargo refuses a cycle. In a --db project the column has a foreign key, so an order for a
customer that does not exist is rejected by Postgres and answered 422 with
pedido.validacion.cliente_id_no_encontrado. GET /pedidos?clienteId= lists one customer’s
orders, and the web form picks the customer from a <select>
(ADR-0022). The
target has to be scaffolded first. See References.
After the scaffold, the files are yours
Section titled “After the scaffold, the files are yours”Everything except the regenerated files is written once and then belongs to you. Change the
model, add methods, rewrite a use case. Running scaffold again for the same entity is refused:
'producto' is already generated — this would overwrite 30 file(s): contextos/producto/dominio/src/modelo.rs contextos/producto/dominio/src/errores.rs contextos/producto/dominio/src/repositorio.rs contextos/producto/dominio/src/pruebas/madres.rs contextos/producto/aplicacion/src/crear_producto.rs contextos/producto/aplicacion/src/obtener_producto.rs contextos/producto/aplicacion/src/listar_productos.rs contextos/producto/aplicacion/src/actualizar_producto.rs contextos/producto/aplicacion/src/borrar_producto.rs contextos/producto/infraestructura/src/repositorio.rs … and 20 more
Error: refusing to overwrite existing files for 'producto'. Re-run with --forzar to overwrite, or remove the files first. Nothing was written.--forzar regenerates the entity and discards your changes in its files. It exists for the
moment right after a scaffold, when you got a field wrong.
Building one layer at a time
Section titled “Building one layer at a time”scaffold is a shortcut for four commands, one crate each. When you want to design the domain
first, or keep an agent’s context small, run them one by one. See
Layer by layer.