puerto 0.7.2

Puerto — Rust full-stack DDD framework CLI. Scaffolds Clean Architecture projects with auto-wired DI, SQLx support, and zero manual wiring. Formerly puerto-framework.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use std::path::Path;

use crate::generators::bootstrap::regenerate_bootstrap;
use crate::generators::naming::{apply, pascal_to_snake, to_pascal_case, write_file};
use crate::patchers::api_rs::patch_api_rs;

pub(crate) const DTO: &str = r#"use business::domain::{snake}::model::{Pascal};
use poem_openapi::Object;
use uuid::Uuid;

#[derive(Debug, Object)]
pub struct {Pascal}Dto {
    pub id: Uuid,
    pub name: String,
}

impl {Pascal}Dto {
    pub fn from_domain(entity: &{Pascal}) -> Self {
        Self {
            id: entity.id,
            name: entity.name.clone(),
        }
    }
}

#[derive(Debug, Object)]
pub struct Create{Pascal}Request {
    pub name: String,
}
"#;

const CRUD_DTO: &str = r#"use business::domain::{snake}::model::{Pascal};
use poem_openapi::Object;
use uuid::Uuid;

#[derive(Debug, Object)]
pub struct {Pascal}Dto {
    pub id: Uuid,
    pub name: String,
}

impl {Pascal}Dto {
    pub fn from_domain(entity: &{Pascal}) -> Self {
        Self {
            id: entity.id,
            name: entity.name.clone(),
        }
    }
}

#[derive(Debug, Object)]
pub struct Create{Pascal}Request {
    pub name: String,
}

#[derive(Debug, Object)]
pub struct Update{Pascal}Request {
    pub name: String,
}
"#;

pub(crate) const RESPONSES: &str = r#"use crate::api::{error::ErrorResponse, {snake}::dto::{Pascal}Dto};
use poem::http::StatusCode;
use poem_openapi::{ApiResponse, payload::Json};

#[derive(ApiResponse)]
pub enum Create{Pascal}Response {
    #[oai(status = 201)]
    Created(Json<{Pascal}Dto>),
    #[oai(status = 400)]
    BadRequest(Json<ErrorResponse>),
    #[oai(status = 409)]
    Conflict(Json<ErrorResponse>),
    #[oai(status = 500)]
    InternalError(Json<ErrorResponse>),
}

impl Create{Pascal}Response {
    pub fn from_status(status: StatusCode, error: Json<ErrorResponse>) -> Self {
        match status {
            StatusCode::BAD_REQUEST => Self::BadRequest(error),
            StatusCode::CONFLICT => Self::Conflict(error),
            _ => Self::InternalError(error),
        }
    }
}
"#;

const CRUD_RESPONSES: &str = r#"use crate::api::{error::ErrorResponse, {snake}::dto::{Pascal}Dto};
use poem::http::StatusCode;
use poem_openapi::{ApiResponse, payload::Json};

#[derive(ApiResponse)]
pub enum Create{Pascal}Response {
    #[oai(status = 201)]
    Created(Json<{Pascal}Dto>),
    #[oai(status = 400)]
    BadRequest(Json<ErrorResponse>),
    #[oai(status = 409)]
    Conflict(Json<ErrorResponse>),
    #[oai(status = 500)]
    InternalError(Json<ErrorResponse>),
}

impl Create{Pascal}Response {
    pub fn from_status(status: StatusCode, error: Json<ErrorResponse>) -> Self {
        match status {
            StatusCode::BAD_REQUEST => Self::BadRequest(error),
            StatusCode::CONFLICT => Self::Conflict(error),
            _ => Self::InternalError(error),
        }
    }
}

#[derive(ApiResponse)]
pub enum Get{Pascal}Response {
    #[oai(status = 200)]
    Ok(Json<{Pascal}Dto>),
    #[oai(status = 404)]
    NotFound(Json<ErrorResponse>),
    #[oai(status = 500)]
    InternalError(Json<ErrorResponse>),
}

impl Get{Pascal}Response {
    pub fn from_status(status: StatusCode, error: Json<ErrorResponse>) -> Self {
        match status {
            StatusCode::NOT_FOUND => Self::NotFound(error),
            _ => Self::InternalError(error),
        }
    }
}

#[derive(ApiResponse)]
pub enum List{Pascal}Response {
    #[oai(status = 200)]
    Ok(Json<Vec<{Pascal}Dto>>),
    #[oai(status = 500)]
    InternalError(Json<ErrorResponse>),
}

impl List{Pascal}Response {
    pub fn from_status(_status: StatusCode, error: Json<ErrorResponse>) -> Self {
        Self::InternalError(error)
    }
}

#[derive(ApiResponse)]
pub enum Update{Pascal}Response {
    #[oai(status = 200)]
    Ok(Json<{Pascal}Dto>),
    #[oai(status = 400)]
    BadRequest(Json<ErrorResponse>),
    #[oai(status = 404)]
    NotFound(Json<ErrorResponse>),
    #[oai(status = 409)]
    Conflict(Json<ErrorResponse>),
    #[oai(status = 500)]
    InternalError(Json<ErrorResponse>),
}

impl Update{Pascal}Response {
    pub fn from_status(status: StatusCode, error: Json<ErrorResponse>) -> Self {
        match status {
            StatusCode::BAD_REQUEST => Self::BadRequest(error),
            StatusCode::NOT_FOUND => Self::NotFound(error),
            StatusCode::CONFLICT => Self::Conflict(error),
            _ => Self::InternalError(error),
        }
    }
}

#[derive(ApiResponse)]
pub enum Delete{Pascal}Response {
    #[oai(status = 204)]
    NoContent,
    #[oai(status = 404)]
    NotFound(Json<ErrorResponse>),
    #[oai(status = 500)]
    InternalError(Json<ErrorResponse>),
}

impl Delete{Pascal}Response {
    pub fn from_status(status: StatusCode, error: Json<ErrorResponse>) -> Self {
        match status {
            StatusCode::NOT_FOUND => Self::NotFound(error),
            _ => Self::InternalError(error),
        }
    }
}
"#;

pub(crate) const ERROR_MAPPER: &str = r#"use business::domain::{snake}::errors::{Pascal}Error;
use poem::http::StatusCode;
use poem_openapi::payload::Json;

use crate::api::error::{ErrorResponse, IntoErrorResponse};

impl IntoErrorResponse for {Pascal}Error {
    fn into_error_response(self) -> (StatusCode, Json<ErrorResponse>) {
        let (status, message) = match &self {
            {Pascal}Error::ValidationError(_) => (StatusCode::BAD_REQUEST, self.to_string()),
            {Pascal}Error::NotFound => (StatusCode::NOT_FOUND, self.to_string()),
            {Pascal}Error::Duplicate => (StatusCode::CONFLICT, self.to_string()),
            {Pascal}Error::RepositoryError => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
            {Pascal}Error::Unknown => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
        };

        (
            status,
            Json(ErrorResponse {
                name: "{snake}_error".into(),
                message,
            }),
        )
    }
}
"#;

pub(crate) const ROUTES: &str = r#"use std::sync::Arc;

use business::{
    application::{snake}::create_{snake}::Create{Pascal}UseCaseImpl,
    domain::{
        {snake}::use_cases::create_{snake}::{Create{Pascal}Params, Create{Pascal}UseCaseTrait},
        logger::LoggerTrait,
    },
};
use poem_openapi::{OpenApi, payload::Json};

use crate::api::error::IntoErrorResponse;
use crate::api::{snake}::dto::{Create{Pascal}Request, {Pascal}Dto};
use crate::api::{snake}::responses::Create{Pascal}Response;

pub struct {Pascal}Api {
    pub create_{snake}: Arc<Create{Pascal}UseCaseImpl>,
    pub logger: Arc<dyn LoggerTrait>,
}

#[OpenApi]
impl {Pascal}Api {
    /// Create a new {Pascal}
    #[oai(path = "/{snake}s", method = "post")]
    async fn create(&self, body: Json<Create{Pascal}Request>) -> Create{Pascal}Response {
        match self
            .create_{snake}
            .execute(Create{Pascal}Params { name: body.name.clone() })
            .await
        {
            Ok(entity) => Create{Pascal}Response::Created(Json({Pascal}Dto::from_domain(&entity))),
            Err(err) => {
                let (status, error) = err.into_error_response();
                self.logger.warn(&format!("create_{snake} error: {}", error.0.message));
                Create{Pascal}Response::from_status(status, error)
            }
        }
    }
}
"#;

const CRUD_ROUTES: &str = r#"use std::sync::Arc;

use business::{
    application::{snake}::{
        create_{snake}::Create{Pascal}UseCaseImpl,
        delete_{snake}::Delete{Pascal}UseCaseImpl,
        get_{snake}::Get{Pascal}UseCaseImpl,
        list_{snake}::List{Pascal}UseCaseImpl,
        update_{snake}::Update{Pascal}UseCaseImpl,
    },
    domain::{
        {snake}::use_cases::{
            create_{snake}::{Create{Pascal}Params, Create{Pascal}UseCaseTrait},
            delete_{snake}::{Delete{Pascal}Params, Delete{Pascal}UseCaseTrait},
            get_{snake}::{Get{Pascal}Params, Get{Pascal}UseCaseTrait},
            list_{snake}::{List{Pascal}Params, List{Pascal}UseCaseTrait},
            update_{snake}::{Update{Pascal}Params, Update{Pascal}UseCaseTrait},
        },
        logger::LoggerTrait,
    },
};
use poem_openapi::{OpenApi, param::Path, payload::Json};
use uuid::Uuid;

use crate::api::error::IntoErrorResponse;
use crate::api::{snake}::dto::{Create{Pascal}Request, Update{Pascal}Request, {Pascal}Dto};
use crate::api::{snake}::responses::{
    Create{Pascal}Response, Delete{Pascal}Response, Get{Pascal}Response, List{Pascal}Response,
    Update{Pascal}Response,
};

pub struct {Pascal}Api {
    pub create_{snake}: Arc<Create{Pascal}UseCaseImpl>,
    pub get_{snake}: Arc<Get{Pascal}UseCaseImpl>,
    pub list_{snake}: Arc<List{Pascal}UseCaseImpl>,
    pub update_{snake}: Arc<Update{Pascal}UseCaseImpl>,
    pub delete_{snake}: Arc<Delete{Pascal}UseCaseImpl>,
    pub logger: Arc<dyn LoggerTrait>,
}

#[OpenApi]
impl {Pascal}Api {
    /// Create a new {Pascal}
    #[oai(path = "/{snake}s", method = "post")]
    async fn create(&self, body: Json<Create{Pascal}Request>) -> Create{Pascal}Response {
        match self
            .create_{snake}
            .execute(Create{Pascal}Params { name: body.name.clone() })
            .await
        {
            Ok(entity) => Create{Pascal}Response::Created(Json({Pascal}Dto::from_domain(&entity))),
            Err(err) => {
                let (status, error) = err.into_error_response();
                self.logger.warn(&format!("create_{snake} error: {}", error.0.message));
                Create{Pascal}Response::from_status(status, error)
            }
        }
    }

    /// Get a {Pascal} by ID
    #[oai(path = "/{snake}s/:id", method = "get")]
    async fn get_by_id(&self, id: Path<Uuid>) -> Get{Pascal}Response {
        match self
            .get_{snake}
            .execute(Get{Pascal}Params { id: id.0 })
            .await
        {
            Ok(entity) => Get{Pascal}Response::Ok(Json({Pascal}Dto::from_domain(&entity))),
            Err(err) => {
                let (status, error) = err.into_error_response();
                self.logger.warn(&format!("get_{snake} error: {}", error.0.message));
                Get{Pascal}Response::from_status(status, error)
            }
        }
    }

    /// List all {Pascal}s
    #[oai(path = "/{snake}s", method = "get")]
    async fn list(&self) -> List{Pascal}Response {
        match self.list_{snake}.execute(List{Pascal}Params).await {
            Ok(entities) => {
                List{Pascal}Response::Ok(Json(entities.iter().map({Pascal}Dto::from_domain).collect()))
            }
            Err(err) => {
                let (status, error) = err.into_error_response();
                self.logger.error(&format!("list_{snake} error: {}", error.0.message));
                List{Pascal}Response::from_status(status, error)
            }
        }
    }

    /// Update a {Pascal}
    #[oai(path = "/{snake}s/:id", method = "put")]
    async fn update(&self, id: Path<Uuid>, body: Json<Update{Pascal}Request>) -> Update{Pascal}Response {
        match self
            .update_{snake}
            .execute(Update{Pascal}Params {
                id: id.0,
                name: body.name.clone(),
            })
            .await
        {
            Ok(entity) => Update{Pascal}Response::Ok(Json({Pascal}Dto::from_domain(&entity))),
            Err(err) => {
                let (status, error) = err.into_error_response();
                self.logger.warn(&format!("update_{snake} error: {}", error.0.message));
                Update{Pascal}Response::from_status(status, error)
            }
        }
    }

    /// Delete a {Pascal}
    #[oai(path = "/{snake}s/:id", method = "delete")]
    async fn delete(&self, id: Path<Uuid>) -> Delete{Pascal}Response {
        match self
            .delete_{snake}
            .execute(Delete{Pascal}Params { id: id.0 })
            .await
        {
            Ok(()) => Delete{Pascal}Response::NoContent,
            Err(err) => {
                let (status, error) = err.into_error_response();
                self.logger.warn(&format!("delete_{snake} error: {}", error.0.message));
                Delete{Pascal}Response::from_status(status, error)
            }
        }
    }
}
"#;

pub fn write_presentation_files(
    pascal: &str,
    snake: &str,
    base: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    write_file(
        &base.join(format!("presentation/src/api/{snake}.rs")),
        "pub mod dto;\npub mod error_mapper;\npub mod responses;\npub mod routes;\n",
    )?;
    write_file(
        &base.join(format!("presentation/src/api/{snake}/dto.rs")),
        &apply(CRUD_DTO, pascal, snake),
    )?;
    write_file(
        &base.join(format!("presentation/src/api/{snake}/responses.rs")),
        &apply(CRUD_RESPONSES, pascal, snake),
    )?;
    write_file(
        &base.join(format!("presentation/src/api/{snake}/error_mapper.rs")),
        &apply(ERROR_MAPPER, pascal, snake),
    )?;
    write_file(
        &base.join(format!("presentation/src/api/{snake}/routes.rs")),
        &apply(CRUD_ROUTES, pascal, snake),
    )?;
    Ok(())
}

pub fn run_generate_presentation(
    name: &str,
    base: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    let pascal = to_pascal_case(name);
    let snake = pascal_to_snake(&pascal);

    if !config.entity.iter().any(|e| e.name == pascal) {
        return Err(format!(
            "{pascal} not found in puerto.toml. Run `puerto generate domain {pascal}` first."
        )
        .into());
    }

    write_presentation_files(&pascal, &snake, base)?;
    patch_api_rs(base, &snake)?;
    regenerate_bootstrap(base)?;

    println!("✓ presentation/        — routes, dto, responses, error_mapper");
    println!("✓ bootstrap.rs         — regenerated");
    println!();
    println!("  All layers wired. Run `make run` to start.");
    Ok(())
}