Skip to content

Declare the entity

nestrs g resource writes the posts feature, its migration and its round trip from one column list; #[expose] derives the wire types from the Post entity.

You generate the posts feature in one command that names a post’s columns, and read the shape it declares — a SeaORM model decorated with #[expose] — from which the macro emits the wire DTO, the create/update inputs, the validator wiring and the JSON schema the HTTP transport reaches for. By the end of this page, nestrs run check passes on a posts feature whose Post has a title and a body.

From the workspace root:

Terminal window
nestrs g resource posts title:string body:text --app blog

Each column after the name is <name>:<type>, the field grammar Rails’ and Phoenix’s generators share: a post has a title, a short string, and a body, a text of any length. The type is one of string, text, integer, bigint, float, boolean, uuid, date and datetime, and a third part, :nullable, lets a row leave the column empty. The key and the timestamps come without asking; named nothing, a resource gets one name:string column.

Your workspace has two apps, hello and blog, so the generator is told which one serves the feature; run from inside apps/blog/, or in a workspace of one app, it would find it alone. It writes the feature, the table’s migration and the round trip, and wires them, in one transaction — a step it cannot take leaves nothing half-written:

  • Directoryapps/blog/
    • Directorysrc/
      • module.rs edited — the feature’s HTTP adapter and what it runs on
    • Directorytests/
      • Directorye2e/
        • main.rs edited — the suite’s boot fixture
        • posts.rs the round trip, which Test it end to end runs
    • Cargo.toml edited — the suite’s dev-dependencies
  • Directorycrates/features/src/
    • Directoryauthn/ the token side of the guards
      • …
    • Directoryauthz/ the policy side, ability.rs
      • …
    • Directoryposts/
      • entity.rs
      • service.rs
      • module.rs
      • mod.rs
      • Directoryhttp/
        • controller.rs
        • module.rs
        • mod.rs
    • lib.rs edited
  • Directorycrates/migrations/src/

Four things arrived that you did not name. authn/ and authz/ are the auth adapter: the generated controller binds AuthnGuard and AuthzGuard, two types your workspace defines rather than the framework, and nestrs g resource writes them when the workspace has none — with a development-only POST /auth/dev-token route and an HS256 secret drawn into the git-ignored .env.local (and another, the suites’, into .env.test). Expose over HTTP reads them. The migration creates the table the entity declares, column for column. The test is the resource’s round trip through blog, written now so the feature is never untested: it posts a value of each column and reads each back. And the edits to the manifests and to blog’s root, which the next pages read as they need them.

The capabilities ride the workspace’s one nest-rs line, which gains features rather than being replaced (nestrs new already put http and seaorm there):

Cargo.toml
[workspace.dependencies]
nest-rs = { version = "7.0", features = ["http", "seaorm", "authz", "authn", "oauth-server"] }
sea-orm = { version = "2.0", default-features = false, features = ["sqlx-postgres", "runtime-tokio", "macros", "with-uuid", "with-chrono"] }
serde = { version = "1.0", features = ["derive"] }
uuid = { version = "1.29", features = ["v7", "serde"] }
crates/features/Cargo.toml
[dependencies]
nest-rs.workspace = true
nest-rs.features = ["seaorm", "authz", "http", "authn", "oauth-server"]
anyhow.workspace = true
tracing.workspace = true
sea-orm = { workspace = true }
serde = { workspace = true }
uuid = { workspace = true }

Three third-party lines arrive beside the anyhow and tracing nestrs new wrote, and each is there because the feature’s own source writes it: sea_orm::entity::prelude::*, serde on the claims the auth adapter derives, Uuid as the primary-key type. The entity itself derives no serde: what #[expose] emits — the wire type’s serde and schemars::JsonSchema, validator::Validate, the judgement of each wire row it builds — is routed back through the framework with a crate = override, so none of it appears here.

The entity carries the two columns you named, between the key and the timestamps. SeaORM owns the column types — a text column says so with column_type, since both are a String to Rust; #[expose] decides which columns cross the wire and which inputs the HTTP layer accepts. Exposure is opt-in — a field surfaces only when it carries #[expose].

crates/features/src/posts/entity.rs
use nest_rs::seaorm::expose;
use sea_orm::entity::prelude::*;
// `soft_delete` + `timestamps` match the three columns this table's migration
// creates, and the `users/` exemplar. `soft_delete` makes DELETE stamp
// `deleted_at` and hides a stamped row from every read; drop it for a resource
// that should really erase rows. `timestamps` emits the `ActiveModelBehavior`,
// so the resource must not also write an empty one.
#[expose(
name = "Post",
service = super::service::PostsService,
soft_delete,
timestamps
)]
#[sea_orm::model]
#[derive(Clone, Debug, DeriveEntityModel)]
#[sea_orm(table_name = "post")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
#[expose]
pub id: Uuid,
#[expose(input(create, update), validate(length(min = 1)))]
pub title: String,
#[sea_orm(column_type = "Text")]
#[expose(input(create, update), validate(length(min = 1)))]
pub body: String,
#[expose]
pub created_at: DateTimeWithTimeZone,
#[expose]
pub updated_at: DateTimeWithTimeZone,
pub deleted_at: Option<DateTimeWithTimeZone>,
}

The crate this page builds on is nest-rs-seaorm — it provides the #[expose] macro, which also writes the wire type’s conversion, judging each row for the caller once a feature adds authorization — so the Model takes no serde (#[expose] refuses one, derived or written by hand), and serializes nowhere but as Post. SeaORM itself is the source of truth for entities, columns, and migrations.

The decorator translates one declaration into every wire surface:

GeneratedWhat it isWhere it surfaces
PostThe wire DTO — every #[expose]d column, no SeaORM internals and nothing left unexposedHTTP responses, OpenAPI schema
CreatePostA struct holding fields marked input(create)POST /posts body
UpdatePostA struct holding fields marked input(update)PUT /posts/{id} body

Its flags declare the behaviour the columns imply. timestamps stamps created_at on insert and updated_at on every write — it writes the entity’s ActiveModelBehavior, so the file carries none of its own. soft_delete turns DELETE into a stamp on deleted_at and hides a stamped row from every read; drop it, and the column, for a resource whose rows are really erased. service = super::service::PostsService names the service that owns the entity, which an exposed relation or another feature’s loader reaches it through.

Two patterns cover this entity; a third shows up when you copy users in api.

AttributeEffect
#[expose]Bare — the field is read-only on the wire (appears in Post), but not in any input
#[expose(input(create, update), validate(length(min = 1)))]Field appears in Post (input implies read) and in CreatePost and UpdatePost, with the validator rule wired
#[expose(input(create))]Field appears in Post and only in CreatePost — common for fields that can be set but not edited
(no #[expose])Field is hidden from Post and from every input — deleted_at here; the ability’s rules still read it, since each row is judged on its whole Model

Exposure is opt-in, so a server-side column — a password hash, a tenant id set from a JWT — stays off the wire by default; api is where unexposed columns and field grants become load-bearing.

The feature root re-exports what other modules import, and nothing more — the entity’s types, the port’s module and service, and the one adapter an app imports. The controller stays private to its folder:

crates/features/src/posts/mod.rs
mod entity;
mod module;
mod service;
pub mod http;
pub use entity::*;
pub use module::PostsModule;
pub use service::PostsService;
pub use http::PostsHttpModule;

It declares no log target: posts emits nothing yet. The day a file of the feature logs, pub const TARGET: &str = "features::posts"; goes at the top, and every event names it.

Terminal window
$ nestrs run check
Checking features v0.1.0
Checking blog v0.1.0
Finished `dev` profile [unoptimized] target(s) in 1.42s

The macro expanded and the entity compiled, so Post, CreatePost and UpdatePost are usable from the rest of the crate. check builds no test target: the generated test compiles when you run it on Test it end to end.

  • A posts feature nestrs g resource wrote, wired into blog.
  • A Post SeaORM entity with id, title, body and the two timestamps, and the migration creating its table.
  • An auto-generated Post wire DTO and CreatePost / UpdatePost input structs.
  • See the security payoff — the next step: run the reference api and watch access control enforced before you grant your own.
  • Entities — the reference page for #[expose] columns and inputs.