Use cases
A use case is one thing your application does: create a product, publish an order, close an account. The five CRUD use cases come with the scaffold. Everything else is a use case you add.
This guide adds cambiar_precio_producto: change a product’s price, refusing anything that is not
a positive amount. Every snippet below was compiled and tested in a generated project.
-
Generate it.
puerto generar caso-de-uso Producto cambiar_precio_productooutput ✓ Use case CambiarPrecioProducto added to Producto: contextos/producto/aplicacion/src/cambiar_precio_producto.rspuerto.toml updated + bootstrap.rs regenerated.ApiProducto now holds `cambiar_precio_producto` — call it from an endpoint in contextos/producto/rest/src/rutas.rs.It writes one file in the
aplicacion_productocrate,contextos/producto/aplicacion/src/cambiar_precio_producto.rs, with everything the use case is: the params, the trait, its double (dobles::MockCambiarPrecioProducto), the implementation and its tests. It adds thepub modto the crate’slib.rsand the action topuerto.toml, regenerates the wiring (presentacion/cableado/andbootstrap.rs) and adds the field toApiProducto. The action must be snake_case. Naming one that exists is refused, and nothing is overwritten (ADR-0004). -
Say what it takes. The params are a guess (
nombre: String). Make them what the use case needs:contextos/producto/aplicacion/src/cambiar_precio_producto.rs use dominio_producto::modelo::{IdProducto, Producto};#[derive(Debug, Clone)]pub struct ParamsCambiarPrecioProducto {pub id: IdProducto,pub precio: i64,} -
Put the rule in the domain. Not in the use case and not in the route: on the entity, where every use case that changes a price goes through it.
contextos/producto/dominio/src/modelo.rs pub fn cambiar_precio(&mut self, precio: i64) -> Result<(), ErrorProducto> {if precio <= 0 {return Err(ErrorProducto::Validacion("precio_no_positivo".into()));}self.precio = precio;self.actualizado_en = chrono::Utc::now();Ok(())} -
Write the use case. It orchestrates: load, apply the rule, save. The implementation is in the same file, below the trait and its double, and starts as a
todo!():contextos/producto/aplicacion/src/cambiar_precio_producto.rs async fn ejecutar(&self,params: ParamsCambiarPrecioProducto,) -> Result<Producto, ErrorProducto> {tracing::info!(id = %params.id, "cambiar_precio_producto: inicio");let mut producto = self.repositorio.buscar_por_id(params.id).await?.ok_or(ErrorProducto::NoEncontrado)?;producto.cambiar_precio(params.precio)?;self.repositorio.guardar(&producto).await?;tracing::info!(id = %producto.id, "cambiar_precio_producto: fin");Ok(producto)}The repository answers
Result<_, ErrorRepositorio>, and?turns that into anErrorProductothrough the generatedFromimpl. A use case logsinicioandfinwith the id, never the params, because they are user data. -
Test it. The generated test is marked
#[ignore = "escribe este test"]so it cannot pass by accident. Replace it:#[tokio::test]async fn deberia_rechazar_el_precio_cuando_no_es_positivo() {// Prepararlet producto = MadreProducto::aleatorio();let id = producto.id;let mut repositorio_doble = MockRepositorioProducto::new();repositorio_doble.expect_buscar_por_id().returning(move |_| Ok(Some(producto.clone())));repositorio_doble.expect_guardar().never();let caso_de_uso = CambiarPrecioProductoImpl {repositorio: Arc::new(repositorio_doble),};// Actuarlet resultado = caso_de_uso.ejecutar(ParamsCambiarPrecioProducto { id, precio: 0 }).await;// Comprobarassert_eq!(resultado.unwrap_err().to_string(),"producto.validacion.precio_no_positivo");}MadreProductolives in the domain crate, behind itspruebasfeature (use dominio_producto::pruebas::madres::MadreProducto;); the generated test module already importsMockRepositorioProducto. -
Expose it. Puerto does not generate the endpoint: an action name says nothing about the method, the path or the body. Add a request DTO and a response enum next to the generated ones, then the route. The
cambiar_precio_productofield inApiProductocarries#[allow(dead_code)]until a route calls it; delete the attribute now.contextos/producto/rest/src/rutas.rs /// Cambia el precio de un Producto#[oai(path = "/productos/:id/precio",method = "put",tag = "ApiTags::Producto")]async fn cambiar_precio(&self,id: Path<Uuid>,cuerpo: Json<PeticionCambiarPrecioProducto>,) -> RespuestaCambiarPrecioProducto {match self.cambiar_precio_producto.ejecutar(ParamsCambiarPrecioProducto {id: IdProducto::from_uuid(id.0),precio: cuerpo.precio,}).await{Ok(entidad) => {RespuestaCambiarPrecioProducto::Ok(Json(DtoProducto::from_dominio(&entidad)))}Err(err) => {let (status, error) = a_respuesta_error(err);tracing::warn!(codigo = %error.0.codigo, "cambiar_precio_producto falló");RespuestaCambiarPrecioProducto::from_status(status, error)}}}contextos/producto/rest/src/dto.rs #[derive(Debug, Object)]#[oai(rename_all = "camelCase")]pub struct PeticionCambiarPrecioProducto {pub precio: i64,}contextos/producto/rest/src/respuestas.rs #[derive(ApiResponse)]pub enum RespuestaCambiarPrecioProducto {#[oai(status = 200)]Ok(Json<DtoProducto>),#[oai(status = 404)]NoEncontrado(Json<RespuestaError>),#[oai(status = 422)]NoProcesable(Json<RespuestaError>),#[oai(status = 500)]ErrorInterno(Json<RespuestaError>),}impl RespuestaCambiarPrecioProducto {pub fn from_status(status: StatusCode, error: Json<RespuestaError>) -> Self {match status {StatusCode::NOT_FOUND => Self::NoEncontrado(error),StatusCode::UNPROCESSABLE_ENTITY => Self::NoProcesable(error),_ => Self::ErrorInterno(error),}}} -
Test the route. The route tests already have a
Doblesstruct with a double for your use case. Drive the realOpenApiService:#[tokio::test]async fn deberia_responder_422_cuando_el_precio_nuevo_no_es_positivo() {// Prepararlet mut dobles = Dobles::default();dobles.cambiar_precio_producto.expect_ejecutar().returning(|_| Err(ErrorProducto::Validacion("precio_no_positivo".into())));// Actuarlet respuesta = dobles.cliente().put(format!("/productos/{}/precio", Uuid::new_v4())).body_json(&PeticionCambiarPrecioProducto { precio: 0 }.to_json()).send().await;// Comprobarrespuesta.assert_status(StatusCode::UNPROCESSABLE_ENTITY);}
Run make test, make lint and make format, and in a web project make web/sync, because the
API changed.
In a project with domain events
Section titled “In a project with domain events”The repository has no guardar there: writes go through the unit of work, so the event is
recorded in the same transaction. The generated implementation already holds a uow_factory.
Step 4 becomes:
let mut uow = self.uow_factory.begin().await?;uow.guardar(&producto).await?;uow.registrar(EventoProducto::Actualizado(SnapshotProducto::from_entidad( &producto,))).await?;uow.commit().await?;with use dominio_producto::eventos::{EventoProducto, SnapshotProducto};. Writing
self.repositorio.guardar(…) there is a compile error, not a bug found in production. See
Domain events.
In a project with auth
Section titled “In a project with auth”A protected use case’s params carry actor: Principal, which the handler fills with auth.0.
Rules that depend on who is asking (“only the owner edits”) go in the use case, returning
ErrorProducto::Prohibido. See Authentication.