Value objects
A value object is a value with a meaning and a rule: an Email is a string, but not every string
is an email. Giving it its own type means the rule is checked once, when the value is built,
and nothing downstream can hand a raw string to code that expects an email.
Declaring one on a field
Section titled “Declaring one on a field”The second part of the field is the value object’s name:
puerto generar scaffold Pedido -- importe:Importe:f64 estado:Estado:enum:Pendiente/Confirmado/Cancelado#[derive(Debug, Clone, Copy, PartialEq)]pub struct Importe(f64);
impl Importe { pub fn new(valor: f64) -> Result<Self, ErrorPedido> { Ok(Self(valor)) }
pub fn valor(&self) -> f64 { self.0 }}new is where the rule goes, and it starts empty because only you know it:
pub fn new(valor: f64) -> Result<Self, ErrorPedido> { if valor <= 0.0 { return Err(ErrorPedido::ImporteInvalido); } Ok(Self(valor))}ErrorPedido::ImporteInvalido is already generated, along with its 422 mapping. The API answers
pedido.importe_invalido, and the web form shows “Importe is not valid” under the amount input.
estado:Estado:enum:Pendiente/Confirmado/Cancelado generates a Rust enum with FromStr and
as_str():
let estado: Estado = "Confirmado".parse()?; // Err(ErrorPedido::EstadoInvalido) for anything elseestado.as_str(); // "Confirmado"It implements FromStr rather than an inherent from_str, so clippy stays quiet and .parse()
needs no import (ADR-0001). On
the wire it is a string. The frontend narrows it to a union, "Pendiente" | "Confirmado" | "Cancelado", and renders a <select>.
Optional and repeated
Section titled “Optional and repeated”puerto generar scaffold Cliente -- apodo:Apodo:opt:String etiquetas:Etiqueta:vec:Stringapodo is an Option<Apodo> and etiquetas a Vec<Etiqueta>. Each element is validated by the
same new.
Shared value objects
Section titled “Shared value objects”When several entities use the same concept, declare it once:
puerto generar objeto-valor Email Stringpuerto generar scaffold Cliente -- email:Email! nombre:Stringpuerto generar scaffold Proveedor -- email:Email nombre:StringThe type is inferred from the declaration, so email:Email is enough. Shared value objects live
in the nucleo crate (nucleo/src/valores.rs), with their own error in nucleo/src/errores.rs,
and puerto.toml records them:
[[objeto_valor]]nombre = "Email"tipo = "String"A shared value object starts with a real rule, a non-empty trimmed value, which you can tighten in one place for every entity:
impl Email { pub fn new(valor: String) -> Result<Self, ErrorEmail> { let recortado = valor.trim().to_string(); if recortado.is_empty() { return Err(ErrorEmail::Invalido); } Ok(Self { valor: recortado }) }}Each entity still reports it in its own terms: a bad email in a customer is
cliente.email_invalido, in a supplier proveedor.email_invalido.
Where value objects stop
Section titled “Where value objects stop”Value objects live in the domain. Infrastructure and the REST crate see the primitive: the row
has a String column and the DTO a String field. The conversion happens at the boundary, in
code Puerto generates: the use case builds the value object from the params, and the row and the
DTO unwrap it with .valor().