Skip to content

CRUD

One #[crud] attribute on a controller or resolver — list, get, create, update, delete are generated, scoped, and masked, all going through the service.

A REST CRUD or a GraphQL CRUD is one attribute on the controller or resolver impl block. #[crud(service = OrgsService)] names the entity’s CrudService, reaches it through the struct’s #[inject] field of that type, types every operation off that service and its entity’s #[expose], synthesises every operation the developer did not hand-write, and re-emits the block under #[routes] (HTTP) or #[operations] (GraphQL). Auth, row-level filtering, by-id binding and each row’s judgement come from the same data context described in Database and Security — #[crud] just wires the endpoints.

Terminal window
cargo add nest-rs --features seaorm

#[expose] is SeaORM’s own decorator, so it comes with the model it decorates: nest_rs::seaorm, one feature. #[crud] belongs to the edge it serves — nest_rs::http::crud, on by default, or nest_rs::graphql::crud.

crates/features/src/orgs/http/controller.rs (from the demo)
use std::sync::Arc;
use nest_rs::http::{controller, crud};
use crate::authn::AuthnGuard;
use crate::authz::AuthzGuard;
use crate::orgs::OrgsService;
#[controller(path = "/orgs")]
#[use_guards(AuthnGuard, AuthzGuard)]
pub struct OrgsController {
#[inject]
svc: Arc<OrgsService>,
}
#[crud(service = OrgsService)]
impl OrgsController {}

The empty impl block is intentional. From this declaration the framework mounts:

VerbPathAuthz checkBodyReturns
GET/orgsRead on Org—200 Vec<Org> + cursor
GET/orgs/{id}Read on Org—200 Org (404/403)
POST/orgsCreate on OrgCreateOrg201 Org + Location
PUT/orgs/{id}Update on OrgUpdateOrg200 Org (404/403)
DELETE/orgs/{id}Delete on Org—204 (404/403)

Every handler delegates to the same OrgsService instance, which goes through Repo against the ambient executor — so reads are pool, mutations sit inside the request’s transaction, and Ability filters every row.

Every type in that table is read off OrgsService: the entity off its CrudService::Entity, the bodies off Creatable::Create and Updatable::Update, and the answer off the entity’s #[expose(name = "Org")] wire type. The entity, the service and its trait impls each state a fact once; the controller states none of them again.

The 201 is a Created<Json<Org>>: it carries Location: /orgs/<id> — the row it just minted, as RFC 9110 §15.3.2 asks. The path is the one the caller posted to, so a global prefix or a /v1 segment is already part of it, and the value is an absolute-path reference: naming a host would mean trusting the Host header. The OpenAPI document reads the status, the header and the body off that type, so a generated client reads the Location rather than discarding it. The resource is keyed by a Uuid, as its by-id routes are.

The update replaces the row’s writable fields, so its verb is PUT (RFC 9110 §9.3.4), never PATCH, which RFC 5789 keeps for a partial change; a PATCH there answers 405, its Allow naming PUT. Update<Name> mirrors the column types the entity exposed with input(update), so a non-Option column is required:

Terminal window
$ curl -X PUT …/posts/$ID -H 'content-type: application/json' -d '{"title":"Updated"}'
{"type":"about:blank","title":"Bad Request","status":400,"detail":"JSON body at `body`: missing","code":"INVALID_ARGUMENT"}

Make a column Option<T> on the entity when callers must be able to omit it — that is the one knob, and it makes the field nullable on the wire too.

crates/features/src/orgs/http/controller.rs
#[crud(
service = OrgsService, // the service the struct injects as Arc<OrgsService>
paginate = cursor, // optional — cursor is already the default; `none` opts out
ops = [list, get, create, update, delete], // optional — omit for all five
api(get(summary = "Get an org by id")), // optional — one operation's OpenAPI text
)]
impl OrgsController {}
  • service is the service’s type. Every operation reaches it through the struct’s #[inject] field holding it, whatever that field is called, so the block may name its host through an alias, an import or another module. A service the struct does not inject fails the build once, saying what to add:

    error[E0277]: `OrgsController` injects no `OrgsService`
    = note: `#[crud(service = …)]` names the type of an `#[inject]` field of its
    host: add `#[inject] svc: Arc<OrgsService>` to `OrgsController`

    A struct injects each type once, since the container holds one: a second field of the same type fails the build at that field.

  • Every type an operation names comes off that service and its entity: the answer is the entity’s #[expose]d wire type (Org), never the SeaORM Model, each row judged for the caller as it is built; the create and update bodies are the service’s Creatable::Create and Updatable::Update, the #[expose(input(create, update))] types (bare CreateOrg / UpdateOrg, not …Dto).

  • ops lists the operations a resource has (ops = [list, get]); omit it for all five. Each write op reads its trait, so one the service does not offer — a create with no Creatable impl — fails the build, never a silent no-op: “OrgsService offers no create: implement Creatable for it, or drop create from #[crud(ops = …)]”.

  • paginate defaults to cursor — every generated list is keyset-paginated (the next page in a Link: <…>; rel="next" header on REST, first/after arguments on GraphQL). paginate = none opts out into the full collection (backstopped by CrudService::list’s hard cap). It configures list and nothing else, so writing it beside an ops that leaves list out fails the build, since the two declarations disagree, and so does writing it beside a list you write by hand.

  • api(<op>(summary = "…", description = "…")) gives a generated route the OpenAPI text a hand-written one carries in #[api]; an operation it does not name keeps its default summary, worded off the controller’s name (OrgsController → Fetch Org by id). Naming an op ops leaves out or one you write by hand fails the build — give your method its own #[api] — and a resolver refuses the key: a GraphQL field you want described is one you write, with its doc comment.

  • The generated get, update and delete read the id from their route’s one path parameter, /{id}, so a controller whose path names a parameter of its own (/orgs/{org}/users) fails the build rather than answering 500 on every request: mount the resource under a path naming none, or write those operations by hand.

#[crud] only generates the operations you did not write. Hand-write the ones that need custom logic — the rest are filled in:

crates/features/src/posts/http/controller.rs
#[crud(service = PostsService)]
impl PostsController {
#[get("/")]
#[authorize(Read, PostEntity)]
async fn list(&self) -> Result<Json<Vec<Post>>> {
Ok(Json(self.svc.published().await?))
}
}

The list method takes over its generated counterpart; the default get, create, update and delete are still emitted. Names match by ident — a hand-written delete cancels the generated one, and a key configuring only a cancelled op (api(delete(…)), or paginate for a hand-written list) fails the build, since nothing generated reads it. An override answers what the generated method does: a hand-written create keeps the 201 and its Location by returning Created<Json<T>> (Responses).

The same attribute, with query/mutation names derived from the resolver’s resource — its name without Resolver, made singular. UsersResolver ⇒ users, user, create_user, update_user, delete_user:

crates/features/src/users/graphql/resolver.rs (from the demo, abridged)
// …
#[resolver]
#[use_guards(AuthzGuard)]
pub struct UsersResolver {
#[inject]
svc: Arc<UsersService>,
}
#[crud(service = UsersService)]
impl UsersResolver {}

Every operation — generated or hand-written — declares its posture with #[authorize(Action, Entity)] (gate, and reads under the caller’s ability) or #[public]; an operation with none does not compile. Posture is always a visible attribute — a parameter type never stands in for it.

Same override rule — a create_user you write takes over its generated twin, and the generated create_user fills the caller’s org exactly as REST’s does.

FormSurfaceWire shape
paginate = cursor (default)HTTP + GraphQLVec<T> body + Link rel="next" header (REST); [T] + first/after arguments (GraphQL)
paginate = noneHTTP + GraphQLfull ability-scoped collection, hard-capped by CrudService::list

Keyset pagination (cursor) is the default — stable under inserts, and the body stays a plain array of wire rows. Those two values are the whole knob: there is no offset mode, and a consumer that needs page numbers plus a total hand-writes that operation on the service. An after no page issued is refused — a 400 on REST, a field error on GraphQL — and never read as the first page.

See Pagination for the shape end to end.

#[crud] adds nothing to the module declaration — the orchestrator on the impl block is what #[controller] / #[resolver] already discover. List the controller (and the service it injects) like any other provider:

crates/features/src/orgs/module.rs
#[module(providers = [OrgsService])]
pub struct OrgsModule;
crates/features/src/orgs/http/module.rs
#[module(imports = [OrgsModule, AuthzModule], providers = [OrgsController])]
pub struct OrgsHttpModule;

The HTTP transport comes with the controller, which brings HttpModule; the unit of work each request runs in activates at the app root with SeaOrmDatabaseModule, which imports the pool it runs on. Importing only OrgsModule (no HTTP module) gives a worker the same OrgsService without mounting the endpoints — that is the port + adapter split this framework is built around.

  • crates/features/src/orgs/ — the empty-impl exemplar (cursor pagination).
  • crates/features/src/users/ — the tenant-scoped exemplar: every operation generated, the create’s org taken from the grant.
  • crates/nest-rs-http-macros/src/crud.rs — the REST expansion.
  • crates/nest-rs-graphql-macros/src/crud.rs — the GraphQL expansion.
  • crates/nest-rs-seaorm/ — CrudService, Access, Repo.
  • crates/nest-rs-seaorm-macros/ — #[expose], the entity’s wire DTO and inputs.
  • Bound mutations — the access check behind every by-id operation, and a hand-written one on a row named by id.
  • Database errors — what a generated operation answers when the database refuses.
  • Entity inputs — the bodies a create and an update take, and the tenant a create fills from the grant.
  • OpenAPI — every generated route ships with an #[api] summary, the right tags, and the response schema of the #[expose]d entity, so the document at GET /api-json composes automatically.