// Las variantes de éxito llevan el DTO o los bytes del fichero.
#![allow(clippy::large_enum_variant)]
use std::sync::Arc;
{% for f in files %}use aplicacion_{{ snake }}::{{ f.descargar }}::{{ "{" }}{{ f.descargar_pascal }}, Params{{ f.descargar_pascal }}};
use aplicacion_{{ snake }}::{{ f.quitar }}::{{ "{" }}{{ f.quitar_pascal }}, Params{{ f.quitar_pascal }}};
use aplicacion_{{ snake }}::{{ f.subir }}::{{ "{" }}{{ f.subir_pascal }}, Params{{ f.subir_pascal }}};
{% endfor %}use dominio_{{ snake }}::modelo::Id{{ pascal }};
use poem::http::StatusCode;
use poem::{Body, Request};
use poem_openapi::param::{Path, Query};
use poem_openapi::payload::{Binary, Json};
use poem_openapi::{ApiResponse, OpenApi, Tags};
{% if protected %}use puerto_web::auth::BearerAuth;
{% endif %}use puerto_web::ficheros::{Descarga, DtoFichero, ErrorSubida, leer_subida, tipo_de};
{% if any_roles %}use puerto_web::requiere_rol;
{% endif %}use puerto_web::RespuestaError;
use uuid::Uuid;
use crate::errores::a_respuesta_error;
/// La misma etiqueta que `rutas.rs`: poem-openapi junta las dos por su nombre.
#[derive(Tags)]
enum ApiTags {
{{ pascal }},
}
/// Las rutas de los ficheros de {{ pascal }} (ADR-0034 de Puerto). Subir es el fichero tal cual en el
/// cuerpo (`Content-Type`, su tipo; `?nombre=`, su nombre); descargar responde sus bytes, en línea
/// solo si es una imagen o un PDF. Va en su propio `Api` para que `rutas.rs` no cambie;
/// `generado/bootstrap.rs` lo monta junto a `Api{{ pascal }}`.
pub struct ApiFicheros{{ pascal }} {
{% for f in files %} pub {{ f.subir }}: Arc<dyn {{ f.subir_pascal }}>,
pub {{ f.descargar }}: Arc<dyn {{ f.descargar_pascal }}>,
pub {{ f.quitar }}: Arc<dyn {{ f.quitar_pascal }}>,
{% endfor %} /// El tamaño máximo de una subida, en bytes (`FICHEROS_TAMANO_MAXIMO`): más es un 413.
pub tamano_maximo: u64,
}
#[OpenApi]
impl ApiFicheros{{ pascal }} {
{%- for f in files %}
/// Subir {% if f.list %}un fichero a{% else %}el fichero de{% endif %} `{{ f.name }}`: {{ pascal }}
#[oai(path = "/{{ plural }}/:id/{{ f.name }}", method = "{% if f.list %}post{% else %}put{% endif %}", tag = "ApiTags::{{ pascal }}")]
{% for role in subir_roles %} #[requiere_rol("{{ role }}")]
{% endfor %} async fn {{ f.subir }}(
&self,
{% if subir_protected %} auth: BearerAuth,
{% endif %} id: Path<Uuid>,
nombre: Query<Option<String>>,
peticion: &Request,
cuerpo: Binary<Body>,
) -> Respuesta{{ f.subir_pascal }} {
let contenido = match leer_subida(cuerpo.0, self.tamano_maximo).await {
Ok(contenido) => contenido,
Err(ErrorSubida::DemasiadoGrande) => {
return Respuesta{{ f.subir_pascal }}::DemasiadoGrande(Json(RespuestaError::from_codigo(
"{{ snake }}.{{ f.name }}_demasiado_grande",
)));
}
Err(ErrorSubida::Ilegible) => {
return Respuesta{{ f.subir_pascal }}::PeticionIncorrecta(Json(RespuestaError::from_codigo(
"{{ snake }}.{{ f.name }}_ilegible",
)));
}
};
let params = Params{{ f.subir_pascal }} {
{% if subir_protected %} actor: auth.0,
{% endif %} id: Id{{ pascal }}::from_uuid(id.0),
nombre: nombre.0.unwrap_or_default(),
tipo_contenido: tipo_de(peticion),
contenido,
};
match self.{{ f.subir }}.ejecutar(params).await {
Ok(fichero) => Respuesta{{ f.subir_pascal }}::{% if f.list %}Creado{% else %}Ok{% endif %}(Json(DtoFichero::from_dominio(&fichero))),
Err(err) => {
let (status, error) = a_respuesta_error(err);
Respuesta{{ f.subir_pascal }}::from_status(status, error)
}
}
}
/// Descargar {% if f.list %}un fichero de{% else %}el fichero de{% endif %} `{{ f.name }}`: {{ pascal }}
#[oai(path = "/{{ plural }}/:id/{{ f.name }}{% if f.list %}/:id_fichero{% endif %}", method = "get", tag = "ApiTags::{{ pascal }}")]
{% for role in descargar_roles %} #[requiere_rol("{{ role }}")]
{% endfor %} async fn {{ f.descargar }}(
&self,
{% if descargar_protected %} auth: BearerAuth,
{% endif %} id: Path<Uuid>,
{% if f.list %} id_fichero: Path<Uuid>,
{% endif %} ) -> Respuesta{{ f.descargar_pascal }} {
let params = Params{{ f.descargar_pascal }} {
{% if descargar_protected %} actor: auth.0,
{% endif %} id: Id{{ pascal }}::from_uuid(id.0),
{% if f.list %} id_fichero: id_fichero.0,
{% endif %} };
match self.{{ f.descargar }}.ejecutar(params).await {
Ok((fichero, contenido)) => Respuesta{{ f.descargar_pascal }}::Ok(Descarga::new(fichero, contenido)),
Err(err) => {
let (status, error) = a_respuesta_error(err);
Respuesta{{ f.descargar_pascal }}::from_status(status, error)
}
}
}
/// Quitar {% if f.list %}un fichero de{% else %}el fichero de{% endif %} `{{ f.name }}`: {{ pascal }}
#[oai(path = "/{{ plural }}/:id/{{ f.name }}{% if f.list %}/:id_fichero{% endif %}", method = "delete", tag = "ApiTags::{{ pascal }}")]
{% for role in subir_roles %} #[requiere_rol("{{ role }}")]
{% endfor %} async fn {{ f.quitar }}(
&self,
{% if subir_protected %} auth: BearerAuth,
{% endif %} id: Path<Uuid>,
{% if f.list %} id_fichero: Path<Uuid>,
{% endif %} ) -> Respuesta{{ f.quitar_pascal }} {
let params = Params{{ f.quitar_pascal }} {
{% if subir_protected %} actor: auth.0,
{% endif %} id: Id{{ pascal }}::from_uuid(id.0),
{% if f.list %} id_fichero: id_fichero.0,
{% endif %} };
match self.{{ f.quitar }}.ejecutar(params).await {
Ok(()) => Respuesta{{ f.quitar_pascal }}::SinContenido,
Err(err) => {
let (status, error) = a_respuesta_error(err);
Respuesta{{ f.quitar_pascal }}::from_status(status, error)
}
}
}
{%- endfor %}
}
{% for f in files %}
#[derive(ApiResponse)]
pub enum Respuesta{{ f.subir_pascal }} {
#[oai(status = {% if f.list %}201{% else %}200{% endif %})]
{% if f.list %}Creado{% else %}Ok{% endif %}(Json<DtoFichero>),
/// El cuerpo no se pudo leer entero.
#[oai(status = 400)]
PeticionIncorrecta(Json<RespuestaError>),
#[oai(status = 401)]
NoAutorizado(Json<RespuestaError>),
#[oai(status = 403)]
Prohibido(Json<RespuestaError>),
#[oai(status = 404)]
NoEncontrado(Json<RespuestaError>),
/// Más grande que `FICHEROS_TAMANO_MAXIMO`.
#[oai(status = 413)]
DemasiadoGrande(Json<RespuestaError>),
#[oai(status = 422)]
NoProcesable(Json<RespuestaError>),
/// El almacén de ficheros{% if subir_protected %}, o quien comprueba el token,{% endif %} no responde.
#[oai(status = 503)]
NoDisponible(Json<RespuestaError>),
#[oai(status = 500)]
ErrorInterno(Json<RespuestaError>),
}
impl Respuesta{{ f.subir_pascal }} {
pub fn from_status(status: StatusCode, error: Json<RespuestaError>) -> Self {
match status {
StatusCode::UNAUTHORIZED => Self::NoAutorizado(error),
StatusCode::FORBIDDEN => Self::Prohibido(error),
StatusCode::NOT_FOUND => Self::NoEncontrado(error),
StatusCode::UNPROCESSABLE_ENTITY => Self::NoProcesable(error),
StatusCode::SERVICE_UNAVAILABLE => Self::NoDisponible(error),
_ => Self::ErrorInterno(error),
}
}
}
#[derive(ApiResponse)]
pub enum Respuesta{{ f.descargar_pascal }} {
/// El contenido: en línea si es una imagen o un PDF; si no, como descarga.
#[oai(status = 200)]
Ok(Descarga),
#[oai(status = 401)]
NoAutorizado(Json<RespuestaError>),
#[oai(status = 403)]
Prohibido(Json<RespuestaError>),
#[oai(status = 404)]
NoEncontrado(Json<RespuestaError>),
/// El almacén de ficheros{% if descargar_protected %}, o quien comprueba el token,{% endif %} no responde.
#[oai(status = 503)]
NoDisponible(Json<RespuestaError>),
#[oai(status = 500)]
ErrorInterno(Json<RespuestaError>),
}
impl Respuesta{{ f.descargar_pascal }} {
pub fn from_status(status: StatusCode, error: Json<RespuestaError>) -> Self {
match status {
StatusCode::UNAUTHORIZED => Self::NoAutorizado(error),
StatusCode::FORBIDDEN => Self::Prohibido(error),
StatusCode::NOT_FOUND => Self::NoEncontrado(error),
StatusCode::SERVICE_UNAVAILABLE => Self::NoDisponible(error),
_ => Self::ErrorInterno(error),
}
}
}
#[derive(ApiResponse)]
pub enum Respuesta{{ f.quitar_pascal }} {
#[oai(status = 204)]
SinContenido,
#[oai(status = 401)]
NoAutorizado(Json<RespuestaError>),
#[oai(status = 403)]
Prohibido(Json<RespuestaError>),
#[oai(status = 404)]
NoEncontrado(Json<RespuestaError>),
/// El almacén de ficheros{% if subir_protected %}, o quien comprueba el token,{% endif %} no responde.
#[oai(status = 503)]
NoDisponible(Json<RespuestaError>),
#[oai(status = 500)]
ErrorInterno(Json<RespuestaError>),
}
impl Respuesta{{ f.quitar_pascal }} {
pub fn from_status(status: StatusCode, error: Json<RespuestaError>) -> Self {
match status {
StatusCode::UNAUTHORIZED => Self::NoAutorizado(error),
StatusCode::FORBIDDEN => Self::Prohibido(error),
StatusCode::NOT_FOUND => Self::NoEncontrado(error),
StatusCode::SERVICE_UNAVAILABLE => Self::NoDisponible(error),
_ => Self::ErrorInterno(error),
}
}
}
{% endfor %}
#[cfg(test)]
mod tests {
{% for f in files %} use aplicacion_{{ snake }}::{{ f.descargar }}::dobles::Mock{{ f.descargar_pascal }};
use aplicacion_{{ snake }}::{{ f.quitar }}::dobles::Mock{{ f.quitar_pascal }};
use aplicacion_{{ snake }}::{{ f.subir }}::dobles::Mock{{ f.subir_pascal }};
{% endfor %} use dominio_{{ snake }}::errores::Error{{ pascal }};
{% if protected %} use poem::{EndpointExt, Route, test::TestClient};
use poem_openapi::OpenApiService;
use puerto_nucleo::auth::dobles::{MadrePrincipal, MockAutenticador};
use puerto_nucleo::auth::{Autenticador, ErrorAuth};
{% else %} use poem::{Route, test::TestClient};
use poem_openapi::OpenApiService;
{% endif %} use puerto_nucleo::ficheros::Fichero;
use super::*;
/// El máximo de los tests: 4 bytes.
const TAMANO_MAXIMO: u64 = 4;
/// Los casos de uso de las rutas, doblados: sin expectativas, fallan si se les llama.
struct Dobles {
{% for f in files %} {{ f.subir }}: Mock{{ f.subir_pascal }},
{{ f.descargar }}: Mock{{ f.descargar_pascal }},
{{ f.quitar }}: Mock{{ f.quitar_pascal }},
{% endfor %} }
impl Dobles {
fn new() -> Self {
Self {
{% for f in files %} {{ f.subir }}: Mock{{ f.subir_pascal }}::new(),
{{ f.descargar }}: Mock{{ f.descargar_pascal }}::new(),
{{ f.quitar }}: Mock{{ f.quitar_pascal }}::new(),
{% endfor %} }
}
fn api(self) -> ApiFicheros{{ pascal }} {
ApiFicheros{{ pascal }} {
{% for f in files %} {{ f.subir }}: Arc::new(self.{{ f.subir }}),
{{ f.descargar }}: Arc::new(self.{{ f.descargar }}),
{{ f.quitar }}: Arc::new(self.{{ f.quitar }}),
{% endfor %} tamano_maximo: TAMANO_MAXIMO,
}
}
}
{% if protected %}
/// Acepta `llamante`{% if caller_roles %} (con los roles de las rutas){% endif %} y `nadie` (sin roles).
fn autenticador() -> Arc<dyn Autenticador> {
let mut doble = MockAutenticador::new();
doble.expect_autenticar().returning(|token| match token {
"llamante" => Ok({% if caller_roles %}MadrePrincipal::new()
.con_roles([{% for role in caller_roles %}"{{ role }}"{% if not loop.last %}, {% endif %}{% endfor %}])
.construir(){% else %}MadrePrincipal::aleatorio(){% endif %}),
"nadie" => Ok(MadrePrincipal::aleatorio()),
_ => Err(ErrorAuth::Invalido),
});
Arc::new(doble)
}
/// Las rutas sobre `dobles`; `autorizacion`, la cabecera de cada petición (`None`: ninguna).
fn cliente_con(dobles: Dobles, autorizacion: Option<&str>) -> TestClient<impl poem::Endpoint> {
let cliente = TestClient::new(
Route::new()
.nest("/", OpenApiService::new(dobles.api(), "test", "1.0"))
.data(autenticador()),
);
match autorizacion {
Some(valor) => cliente.default_header("Authorization", valor),
None => cliente,
}
}
/// Las rutas sobre `dobles`, con la sesión de quien tiene los roles de todas.
fn cliente(dobles: Dobles) -> TestClient<impl poem::Endpoint> {
cliente_con(dobles, Some("Bearer llamante"))
}
{% else %}
/// Las rutas sobre `dobles`.
fn cliente(dobles: Dobles) -> TestClient<Route> {
TestClient::new(Route::new().nest("/", OpenApiService::new(dobles.api(), "test", "1.0")))
}
{% endif %}{% for f in files %}
fn ruta_{{ f.name }}() -> String {
format!("/{{ plural }}/{}/{{ f.name }}", Uuid::new_v4())
}
{% if f.list %}
fn ruta_{{ f.name }}_fichero() -> String {
format!("/{{ plural }}/{}/{{ f.name }}/{}", Uuid::new_v4(), Uuid::new_v4())
}
{% endif %}
#[tokio::test]
async fn deberia_responder_{% if f.list %}201{% else %}200{% endif %}_con_el_fichero_cuando_se_sube_a_{{ f.name }}() {
// Preparar
let mut dobles = Dobles::new();
dobles
.{{ f.subir }}
.expect_ejecutar()
.withf(|params| params.nombre == "foto.png" && params.tipo_contenido == "image/png")
.return_once(|params| Ok(Fichero::nuevo(¶ms.nombre, ¶ms.tipo_contenido, 3)));
let cliente = cliente(dobles);
// Actuar
let respuesta = cliente
.{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
.query("nombre", &"foto.png")
.content_type("image/png")
.body(vec![1u8, 2, 3])
.send()
.await;
// Comprobar
respuesta.assert_status(StatusCode::{% if f.list %}CREATED{% else %}OK{% endif %});
let json = respuesta.json().await;
let fichero = json.value().object();
fichero.get("nombre").assert_string("foto.png");
fichero.get("tipoContenido").assert_string("image/png");
fichero.get("tamano").assert_i64(3);
}
#[tokio::test]
async fn deberia_responder_413_sin_llamar_al_caso_de_uso_cuando_{{ f.name }}_pasa_del_maximo() {
// Preparar — sin expectativas: nunca se llega al caso de uso
let cliente = cliente(Dobles::new());
// Actuar
let respuesta = cliente
.{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
.content_type("application/octet-stream")
.body(vec![0u8; TAMANO_MAXIMO as usize + 1])
.send()
.await;
// Comprobar
respuesta.assert_status(StatusCode::PAYLOAD_TOO_LARGE);
respuesta
.json()
.await
.value()
.object()
.get("codigo")
.assert_string("{{ snake }}.{{ f.name }}_demasiado_grande");
}
#[tokio::test]
async fn deberia_responder_422_cuando_{{ f.name }}_llega_vacio() {
// Preparar
let mut dobles = Dobles::new();
dobles
.{{ f.subir }}
.expect_ejecutar()
.return_once(|_| Err(Error{{ pascal }}::Validacion("{{ f.name }}_vacio".into())));
let cliente = cliente(dobles);
// Actuar
let respuesta = cliente
.{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
.content_type("application/octet-stream")
.body(Vec::<u8>::new())
.send()
.await;
// Comprobar
respuesta.assert_status(StatusCode::UNPROCESSABLE_ENTITY);
respuesta
.json()
.await
.value()
.object()
.get("codigo")
.assert_string("{{ snake }}.validacion.{{ f.name }}_vacio");
}
#[tokio::test]
async fn deberia_servir_en_linea_una_imagen_de_{{ f.name }}() {
// Preparar
let mut dobles = Dobles::new();
dobles
.{{ f.descargar }}
.expect_ejecutar()
.return_once(|_| Ok((Fichero::nuevo("foto.png", "image/png", 3), vec![1, 2, 3])));
let cliente = cliente(dobles);
// Actuar
let respuesta = cliente.get(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;
// Comprobar
respuesta.assert_status_is_ok();
respuesta.assert_header("content-type", "image/png");
respuesta.assert_header("content-disposition", "inline; filename*=UTF-8''foto.png");
respuesta.assert_header("x-content-type-options", "nosniff");
respuesta.assert_bytes(vec![1u8, 2, 3]).await;
}
#[tokio::test]
async fn deberia_servir_como_descarga_un_html_de_{{ f.name }}() {
// Preparar
let mut dobles = Dobles::new();
dobles
.{{ f.descargar }}
.expect_ejecutar()
.return_once(|_| Ok((Fichero::nuevo("pagina.html", "text/html", 3), vec![1, 2, 3])));
let cliente = cliente(dobles);
// Actuar
let respuesta = cliente.get(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;
// Comprobar
respuesta.assert_status_is_ok();
respuesta.assert_header("content-type", "application/octet-stream");
respuesta.assert_header("content-disposition", "attachment; filename*=UTF-8''pagina.html");
respuesta.assert_header("x-content-type-options", "nosniff");
}
#[tokio::test]
async fn deberia_responder_404_cuando_{{ f.name }}_no_tiene_el_fichero() {
// Preparar
let mut dobles = Dobles::new();
dobles
.{{ f.descargar }}
.expect_ejecutar()
.return_once(|_| Err(Error{{ pascal }}::FicheroNoEncontrado("{{ f.name }}".into())));
let cliente = cliente(dobles);
// Actuar
let respuesta = cliente.get(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;
// Comprobar
respuesta.assert_status(StatusCode::NOT_FOUND);
respuesta
.json()
.await
.value()
.object()
.get("codigo")
.assert_string("{{ snake }}.{{ f.name }}_no_encontrado");
}
#[tokio::test]
async fn deberia_responder_204_cuando_se_quita_{{ f.name }}() {
// Preparar
let mut dobles = Dobles::new();
dobles.{{ f.quitar }}.expect_ejecutar().return_once(|_| Ok(()));
let cliente = cliente(dobles);
// Actuar
let respuesta = cliente.delete(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;
// Comprobar
respuesta.assert_status(StatusCode::NO_CONTENT);
}
#[tokio::test]
async fn deberia_responder_503_cuando_el_almacen_de_{{ f.name }}_no_responde() {
// Preparar
let mut dobles = Dobles::new();
dobles
.{{ f.quitar }}
.expect_ejecutar()
.return_once(|_| Err(Error{{ pascal }}::AlmacenNoDisponible));
let cliente = cliente(dobles);
// Actuar
let respuesta = cliente.delete(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;
// Comprobar
respuesta.assert_status(StatusCode::SERVICE_UNAVAILABLE);
}
{%- if subir_protected %}
#[tokio::test]
async fn deberia_responder_401_cuando_se_sube_a_{{ f.name }}_sin_token() {
// Preparar — sin expectativas: nunca se llega al caso de uso
let cliente = cliente_con(Dobles::new(), None);
// Actuar
let respuesta = cliente
.{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
.content_type("application/octet-stream")
.body(vec![1u8])
.send()
.await;
// Comprobar
respuesta.assert_status(StatusCode::UNAUTHORIZED);
}
{%- endif %}
{%- if subir_roles %}
#[tokio::test]
async fn deberia_responder_403_cuando_se_sube_a_{{ f.name }}_sin_el_rol() {
// Preparar — sin expectativas: nunca se llega al caso de uso
let cliente = cliente_con(Dobles::new(), Some("Bearer nadie"));
// Actuar
let respuesta = cliente
.{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
.content_type("application/octet-stream")
.body(vec![1u8])
.send()
.await;
// Comprobar
respuesta.assert_status(StatusCode::FORBIDDEN);
}
{%- endif %}
{% endfor %}}